0

I have a student work, but i have some problems. While im trying to open my png file, by this code:

File file = new File("png.png");
byte[] fileContent = Files.readAllBytes(file.toPath());

for (int i=0; i<fileContent.length; i++)
    System.out.println(fileContent[i]);

I have noticed that my bytes, bigger than 128, are converted into minus values. For example first Value (in PNG structure) is 137, in my eclips view it's -119. What's wrong? am I doing something wrong, or i have to convert somehow that minus values into something different?

I want to do adding operations on this structure (but firstly i need to earn a knowledge about are that bits...)

Potato
  • 172
  • 1
  • 12
  • Dude, your reaction is faster than Chuck Norris... Thanks a lot. i couldn't find my answer, sorry for that. :) – Potato Nov 26 '16 at 12:57
  • because byte in Java is signed. [How can I read a file as unsigned bytes in Java?](http://stackoverflow.com/q/5144080/995714) – phuclv Nov 26 '16 at 13:02

1 Answers1

0

A byte can only accept values between -128 and +127. The 137 you mentioned will wrap around to become -119.

If you absolutely need an unsigned number, you will need to cast it to an int and perform appropriate bit masking:

int value = ((int)fileContent[i]) & 0xff;
Joe C
  • 15,324
  • 8
  • 38
  • 50