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.
Java doesn't have unsigned bytes (0 to 255). To make an unsigned byte, we can cast the byte into an int and mask (bitwise and) the new int with a 0xff to get the last 8 bits or prevent sign extension.
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
Int to Byte Using byteValue() Method in Java We can also use the byteValue() method of the Integer class to get the byte value after conversion. This method returns a signed value. So, use it only if you want to get a signed result.
Java Long parseUnsignedLong() MethodAn unsigned integer maps the value which is associated with the negative number to the positive number that is larger than the MAX_VALUE. The total characters in the string must all be digits with the specified radix except the first character which can be an ASCII plus sign.
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.
With the unsigned API in Java 8 you have Byte.toUnsignedInt
. That'll be a lot cleaner than manually casting and masking out.
To convert the int
back to byte
after messing with it of course you just need a cast (byte)value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With