tyr tyr - 1 year ago 75
Java Question

How can I read a file as unsigned bytes in Java?

How can I read a file to bytes in Java?

It is important to note that all the bytes need to be positive, i.e. the negative range cannot be used.

Can this be done in Java, and if yes, how?

I need to be able to multiply the contents of a file by a constant. I was assuming that I can read the bytes into a BigInteger and then multiply, however since some of the bytes are negative I am ending up with 12 13 15 -12 etc and get stuck.

Answer Source

Well, Java doesn't have the concept of unsigned bytes... the byte type is always signed, with values from -128 to 127 inclusive. However, this will interoperate just fine with other systems which have worked with unsigned values for example, C# code writing a byte of "255" will produce a file where the same value is read as "-1" in Java. Just be careful, and you'll be okay.

EDIT: You can convert the signed byte to an int with the unsigned value very easily using a bitmask. For example:

byte b = -1; // Imagine this was read from the file
int i = b & 0xff;
System.out.println(i); // 255

Do all your arithmetic using int, and then cast back to byte when you need to write it out again.

You generally read binary data from from files using FileInputStream or possibly FileChannel.

It's hard to know what else you're looking for at the moment... if you can give more details in your question, we may be able to help you more.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download