문제

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

도움이 되었습니까?

해결책

A much simpler approach is to cast it:

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

Prints -52.

다른 팁

You can cast it:

Byte test = (byte) number;

Use this:

  byte b = (byte) ((0xFF) & number);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top