This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
} |
0 件のコメント:
コメントを投稿