Java's byte type stores 8 bits (= 1 byte) of data.
The bit string (binary number) stored in byte is expressed in hexadecimal and decimal as follows.
| Bit string(Binary number) | Hexadecimal | Decimal number |
|---|---|---|
| 00000000 | 00 | 0 |
| ~ | ~ | ~ |
| 01111111 | 7F | 127 |
| 10000000 | 80 | -128 |
| ~ | ~ | ~ |
| 11111111 | FF | -1 |
This section describes how to display in binary notation and how to display in hexadecimal notation.
--Binary notation
1: byte b = 10;
2: int i = Byte.toUnsignedInt(b); //Unsigned conversion
3: String str = Integer.toBinaryString(i); //Get binary string
4: str = String.format("%8s", str).replace(' ', '0'); //0 padding
5: System.out.println(str);
--Hexary notation
1: byte b = 10;
2: System.out.print(String.format("%02X", b));
The output results of each are as follows.
Binary number: 00001010
Hexagon: 0A
If you compare the output methods, you can see that the binary notation requires various conversions.
I will explain what kind of conversion is being performed in binary notation. First from the second line.
2nd line: Convert from byte type to ʻint` type
2: int i = Byte.toUnsignedInt(b); //Unsigned conversion
At this time, the point is that unsigned conversion is performed. The reason is that the upper 24 bits of the int type are set to 0.
| byte type(integer) | int type |
int type |
|---|---|---|
| 00000001(1) | 00000000000000000000000000000001(1) | 00000000000000000000000000000001(1) |
| 11111111(-1) | 00000000000000000000000011111111(255) | 11111111111111111111111111111111(-1) |
Line 3: Get the binary string (bit string) of a ʻint` type variable
3: String str = Integer.toBinaryString(i); //Get binary string
At this time, the high-order 0 is ignored. This is why we were doing unsigned conversions.
| int type(integer) | Binary string |
|---|---|
| 00000000000000000000000000000001(1) | 1 |
| 00000000000000000000000011111111(255) | 11111111 |
4th line: 0 padding the acquired character string
4: str = String.format("%8s", str).replace(' ', '0'); //0 padding
Specifically, after padding with whitespace using a formatted string, the whitespace is replaceed to 0.
When I was checking the operation of the program, I suddenly wanted to check the contents of byte [], and when I searched for a method, I struggled unexpectedly, so I left a memo on how to realize it. It's a small story, but I hope it helps someone.
Recommended Posts