Tony
Tony

Reputation: 3638

Java int to unsigned byte

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

Upvotes: 3

Views: 10234

Answers (3)

Andy Thomas
Andy Thomas

Reputation: 86381

Use this:

  byte b = (byte) ((0xFF) & number);

Upvotes: 1

laz
laz

Reputation: 28638

You can cast it:

Byte test = (byte) number;

Upvotes: 4

Bernhard Barker
Bernhard Barker

Reputation: 55589

A much simpler approach is to cast it:

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

Prints -52.

Upvotes: 15

Related Questions