unsigned byte ã int ã«å¤æããã
ãbyte & 0xFFãã¨ãã¾ãã(âJava FAQ - S007 Q-11 - byte を符号無しとして(unsigned byte として)int と相互に変換するには?ãã)
byte b = -3; int i = b & 0xFF; System.out.println( i ); // 253
解説ã¯ã↑のサイトã®éãã§ããã
- byteãæ®éã«ãã£ã¹ãããã¨ã符å·æ¡å¼µã¨ããã«ãããintã§ã®éunsigned byteå¤ãã«ãªã£ã¦ãã¾ãã
- ããã§ãããã« 0xFF ã¨ã®è«çç©ãåããã¨ã§ã
- æ¡å¼µãããé¨åãé¤ããå¤ãåãåºãã¾ãã
// byteå¤ byte b = -3; System.out.println( toBinary(b) ); // 11111101 // æ®éã«ãã£ã¹ãããã¨ãintã§ã®-3ã«ãªã£ã¦ãã¾ãã int i = b; System.out.println( toBinary(i) ); // 11111111111111111111111111111101 // ãã㧠0xFF 㧠& ãåãã¨ã System.out.println( toBinary(0xFF) ); // 00000000000000000000000011111111 // ãã¾ããã¨unsignedã®å¤ãåãåºããã System.out.println( toBinary(b & 0xFF) ); // 00000000000000000000000011111101 ... public static String toBinary( byte number ) { StringBuilder b = new StringBuilder(8); for ( int i = 7; i >=0; i-- ) { b.append( (number & (1 << i)) >> i ); } return b.toString(); } public static String toBinary( int number ) { StringBuilder b = new StringBuilder(32); for ( int i = 31; i >=0; i-- ) { b.append( (number & 1L << i ) >> i ); } return b.toString(); }
ããããªãããã°ã£ã¦ãæ°ããããªã¼ãã¨ã¯æã£ã¦ãããã ã