Question

Long story short, I'm reading some integer values from one file, then I need to store them in a byte array, for later writing to another file.

For example:

int number = 204;
Byte test = new Byte(Integer.toString(number));

This code throws:

java.lang.NumberFormatException: Value out of range. Value:"204" Radix:10

The problem here is that a byte can only store from -127 - 128, so obviously that number is far too high. What I need to do is have the number signed, which is the value -52, which will fit into the byte. However, I'm unsure how to accomplish this.

Can anyone advise?

Thanks

Was it helpful?

Solution

A much simpler approach is to cast it:

int number = 204;
byte b = (byte)number;
System.out.println(b);

Prints -52.

OTHER TIPS

You can cast it:

Byte test = (byte) number;

Use this:

  byte b = (byte) ((0xFF) & number);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top