// JRE 1.6.0_07
// java.lang.Integer
// Integerクラスのビット操作関連メソッド
// tag bit
//////////////////////////////////////////////////
// SIZE;
// Integerのビットのサイズ
System.out.println( Integer.SIZE );
// => 32
//////////////////////////////////////////////////
// bitCount
for( int i = 100; i < 103; i++ ) {
// バイナリ表現
String bin = Integer.toBinaryString( i );
// bitCountの結果
int cnt = Integer.bitCount( i );
// 結果表示
System.out.println( bin + " : " + cnt );
}
// 結果
// 2進数表示 : bitCount結果
// 1100100 : 3
// 1100101 : 4
// 1100110 : 4
// 1100111 : 5
// 1101000 : 3
// 1の数がカウントされていることが分かる
// ちなみにbitCountのソースでは黒魔術が使われている
//////////////////////////////////////////////////
// highestOneBit
// 1が立っているビットの中で一番左
for( int i = -1; i < 5; i++ ) {
// バイナリ表現
String bin = Integer.toBinaryString( i );
// highestOneBitの結果
int cnt = Integer.highestOneBit( i );
// 結果表示
System.out.println( bin + " : " + cnt );
}
// 結果
// 2進数表示 : highestOneBit結果
// 11111111111111111111111111111111 : -2147483648
// 0 : 0
// 1 : 1
// 10 : 2
// 11 : 2
// 100 : 4
// 一番左端のビット以外が0だった場合の値が出力される
// これのソースも黒魔術チックだけど、bitCountよりは数段分かり易い
//////////////////////////////////////////////////
// lowestOneBit
// 1が立っているビットの中で一番右
for( int i = -1; i < 5; i++ ) {
// バイナリ表現
String bin = Integer.toBinaryString( i );
// lowestOneBitの結果
int cnt = Integer.lowestOneBit( i );
// 結果表示
System.out.println( bin + " : " + cnt );
}
// 結果
// 2進数表示 : lowestOneBit結果
// 11111111111111111111111111111111 : 1
// 0 : 0
// 1 : 1
// 10 : 2
// 11 : 1
// 100 : 4
//////////////////////////////////////////////////
// reverse
// ビットを逆転する
for( int i = 17; i < 20; i++ ) {
// バイナリ表現
String bin = Integer.toBinaryString( i );
// bitCountの結果
int cnt = Integer.reverse( i );
// 結果表示
System.out.println( i + " : " + bin + " | " +
Integer.toBinaryString( cnt ) + " : " + cnt );
}
// 結果
// 17 : 10001 | 10001000000000000000000000000000 : -2013265920
// 18 : 10010 | 1001000000000000000000000000000 : 1207959552
// 19 : 10011 | 11001000000000000000000000000000 : -939524096
// 32ビットで考えて逆転させる
//////////////////////////////////////////////////
// reverseBytes
// バイト単位で逆転する
for( int i = 17; i < 20; i++ ) {
// バイナリ表現
String bin = Integer.toHexString( i );
// bitCountの結果
int cnt = Integer.reverse( i );
// 結果表示
System.out.println( i + " : " + bin + " | " +
Integer.toHexString( cnt ) + " : " + cnt );
}
// 結果
// 元の数字(10進) : 元の数字(16進数) | 変換後の数字(16進数) : 変換後の数字(10進)
// 17 : 11 | 88000000 : -2013265920
// 18 : 12 | 48000000 : 1207959552
// 19 : 13 | c8000000 : -939524096
//////////////////////////////////////////////////
// rotateLeft
// バイトを左に指定数だけ進める
// とりあえず「8」という数を0〜3までシフトしてみる
int num = 8;
for( int i = 0; i < 4; i++ ) {
int ret = Integer.rotateLeft( num, i );
System.out.println( Integer.toBinaryString( i ) + " | " +
Integer.toBinaryString( ret ) + " : " + ret );
}
// 結果
// 0 | 1000 : 8
// 1 | 10000 : 16
//10 | 100000 : 32
//11 | 1000000 : 64
2009年07月12日
【1日1Java】Integerのビット操作関連メソッド
Integerクラスにビット操作関連メソッドがいくつかいたので使ってみる