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|
This section describes how to display in binary notation and how to display in hexadecimal 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);
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
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|
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
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.