1

I don't know if this is a bug or there is something i'm missing here.I'm trying to get the exact bytes of a file so i can work on some.

So i have a byte[1024] array to get the first 1024 bytes of it,a char[1024] array,and i am doing an Integer.toBinaryString on each byte to see it's value

But in some positions,instead of an 8 bit byte,there are values like index[20]=11111111111111111111111111111111 index[21]=11111111111111111111111111111110

How can a byte be 32 bits?

In this case it's supposed to be a UTF-16 BOM and according to my test it should be 255 254 ,so only the last 8 of each index should be there

Thank you in advance for the help

dac1n
  • 309
  • 2
  • 11

2 Answers2

2

Both bytes and ints are signed in Java.

The negative values are stored as two's complements.

So a -1 byte is represented as '1111 1111'. This is converted to -1 int which is represented as '1111 1111 1111 1111 1111 1111 1111 1111' which is what you are seeing.

If you have a byte b and want to see its exact bit-by-bit representation you need to do ((int) b) & 0xFF.

This will convert your byte to an int and will reset all the bits "above" the first byte of that new int to zero.

metlos
  • 306
  • 2
  • 5
1

You're calling Integer.toBinaryString(), which takes an int parameter.

The byte you pass in is automatically cast to int. An int has 4 bytes, hence you get the 32 bits you're seeing.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • The rest of the bytes are printed ok.But in any case, is there another method where i can simply copy the byte as a string? I want to print the actual byte on a file,like "00000101 on position i",not decode it into anything else – dac1n May 19 '16 at 08:56
  • &0xFF seems to work.However, just to be sure,if i do just a println(byte[i]),and the console displays an integer ,does it still assume it's a signed integer like my mistake above? I just want to make sure that byte& 0xFF is exactly the contents of the file – dac1n May 19 '16 at 09:11