3

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

4
  • You need to take an array of bytes(usually buffer) .. and have to store each byte Commented May 17, 2013 at 15:10
  • Possible duplicate: stackoverflow.com/questions/4266756/… Commented May 17, 2013 at 15:11
  • if you want to preserve integer's value then you cant cast it to byte ? you need to read all the bytes from file. Commented May 17, 2013 at 15:17
  • possible duplicate of How to Convert Int to Unsigned Byte and Back Commented May 20, 2013 at 13:38

3 Answers 3

15

A much simpler approach is to cast it:

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

Prints -52.

Sign up to request clarification or add additional context in comments.

Comments

4

You can cast it:

Byte test = (byte) number;

Comments

1

Use this:

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

2 Comments

I don't think you need to & it with 0xFF. It seems to output the same with or without it. And yes, I did try with numbers > 255.
For the compiler, it's not necessary in Java, for this narrowing conversion from int to byte. However, it explicitly documents that you're intentionally using only the least-significant byte.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.