2014年8月11日月曜日

byte型変数を2進数文字列に変換する

Javaのbyte変数をInteger#toBinaryStringで変換しても値がマイナスの場合はうまく変換できないし、8桁にならないので、byte変数を実際の2進数の文字列に変換するようなメソッドをいくつか作成した。最後のtoBinaryString4で0xFFとのANDをとっている理由はByte型からInt型への変換を本気で考えるに任せます。こうゆう知っている人にとっては当たり前だけど知らない人にとっては理解するのに時間がかかる「ちょっとしたこと」をインターネットで共有できるようになったのは大きいと思う。
public class MyByte {
public static void main(String[] args) {
byte b = (byte) 0b10101010;
System.out.println(MyByte.toBinaryString1(b));
System.out.println(MyByte.toBinaryString2(b));
System.out.println(MyByte.toBinaryString3(b));
System.out.println(MyByte.toBinaryString4(b));
}
public static String toBinaryString1(byte b) {
int[] i = new int[8];
StringBuffer bs = new StringBuffer();
i[0] = (b & 0x80) >>> 7;
i[1] = (b & 0x40) >>> 6;
i[2] = (b & 0x20) >>> 5;
i[3] = (b & 0x10) >>> 4;
i[4] = (b & 0x08) >>> 3;
i[5] = (b & 0x04) >>> 2;
i[6] = (b & 0x02) >>> 1;
i[7] = (b & 0x01) >>> 0;
for (int j = 0; j < 8; j++) {
bs.append(i[j]);
}
return bs.toString();
}
public static String toBinaryString2(byte b) {
int[] i = new int[8];
StringBuffer bs = new StringBuffer();
i[0] = (b & 0b10000000) >>> 7;
i[1] = (b & 0b01000000) >>> 6;
i[2] = (b & 0b00100000) >>> 5;
i[3] = (b & 0b00010000) >>> 4;
i[4] = (b & 0b00001000) >>> 3;
i[5] = (b & 0b00000100) >>> 2;
i[6] = (b & 0b00000010) >>> 1;
i[7] = (b & 0b00000001) >>> 0;
for (int j = 0; j < 8; j++) {
bs.append(i[j]);
}
return bs.toString();
}
public static String toBinaryString3(byte b) {
StringBuffer bs = new StringBuffer();
for (int j = 0; j < 8; j++) {
int k = (b & 1 << (7 - j)) >>> (7 - j);
bs.append(k);
}
return bs.toString();
}
public static String toBinaryString4(byte b) {
return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
}
}
view raw MyByte.java hosted with ❤ by GitHub

0 件のコメント: