I want to display the number 192 (this is a special case, so I have an array of type byte ) in binary form on the console. I do this:

 byte b = (byte) 192; System.out.println(Integer.toBinaryString((int) b)); 

As a result, I get:

 11111111111111111111111111000000 

This is not exactly what I expected. How do i get my 11000000 ?

1 answer 1

UPD . The author dramatically changed the question, so the answer can be read immediately with UPD1 .

For example:

 System.out.println(Integer.toBinaryString(192)); 

And why do you convert int to byte - very incomprehensible.

Ps. The Integer.toBinaryString(...) method returns a string without leading zeros. That is, when performing:

 System.out.println(Integer.toBinaryString(1)); 

You'll get:

 1 

If you need zeros at the beginning of a line, you can, for example, do this:

 System.out.println(String.format("%8s", Integer.toBinaryString(1)).replace(' ', '0')); 

UPD 1 .

byte is an 8-bit type ( with a sign ), its range is [-(2^8)/2;(2^8)/2 - 1] , that is, [-128;127] .

Perform conversion:

 byte b = (byte) 192; 

happens as follows:

Since 192 does not fit in byte , the remainder of dividing the number 192 by the range of byte values ​​is calculated:

 192 % 2^8 = 192 

Since the remainder of the division still does not fit into the byte , then the size of the byte range is subtracted from the remainder of the division, that is, from the number 192 :

 192 - 256 = -64 

As a result, the variable b will contain the value -64 .

  • Corrected and clarified the question. I just need to convert the type byte . - faoxis
  • @faoxis, Why do you convert int to byte ? The number 192 in the byte does not fit. - post_zeew 2:22 pm
  • Why It's less than 255. - faoxis
  • 2
    @faoxis, byte - 8-bit type (with a sign), its range of values ​​is [-(2^8)/2;(2^8)/2 - 1] , that is, [-128;127] . - post_zeew