ああビットビットビット 2011/01/21

Javaです。Integer.toBinaryStringはちょっとかなり自分のニーズとかけはなれた仕様だなーと思う今日この頃です。
ビットとバイトの関係いまだに頭が混乱します。
ビットのたちぐあいを8ビット、えーと1バイト限定で。

public class aBitBitBit {

public static void main(String[] args) {
System.out.println(binstr(0));
System.out.println(binstr(1));
System.out.println(binstr(2));
System.out.println(binstr(3));
System.out.println(binstr(4));
System.out.println(binstr(8));
System.out.println(binstr(16));
System.out.println(binstr(32));
System.out.println(binstr(64));
System.out.println(binstr(128));
System.out.println(binstr(255));
System.out.println(binstr(256));
System.out.println(binstr(-1));
System.out.println(binstr(0x1));
System.out.println(binstr(0xfe));
System.out.println(binstr(0xff));
}

static String binstr(int b) {
StringBuilder builder = new StringBuilder();

int[] is = { 128, 64, 32, 16, 8, 4, 2, 1 };
for (int i : is) {
if (0 < (b & i)) {
builder.append("1");
} else {
builder.append("0");
}
}

return new String(builder);
}

}


実行結果はこんな感じ
00000000
00000001
00000010
00000011
00000100
00001000
00010000
00100000
01000000
10000000
11111111
00000000
11111111
00000001
11111110
11111111

: