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

Tony
  • 3,587
  • 8
  • 44
  • 77
  • You need to take an array of bytes(usually buffer) .. and have to store each byte – Pragnani May 17 '13 at 15:10
  • Possible duplicate: http://stackoverflow.com/questions/4266756/can-we-make-unsigned-byte-in-java – DeadlyJesus May 17 '13 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. – Peeyush May 17 '13 at 15:17
  • possible duplicate of [How to Convert Int to Unsigned Byte and Back](http://stackoverflow.com/questions/7401550/how-to-convert-int-to-unsigned-byte-and-back) – fglez May 20 '13 at 13:38

3 Answers3

15

A much simpler approach is to cast it:

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

Prints -52.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
4

You can cast it:

Byte test = (byte) number;
laz
  • 28,320
  • 5
  • 53
  • 50
1

Use this:

  byte b = (byte) ((0xFF) & number);
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • 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. – Bernhard Barker May 17 '13 at 15:17
  • 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. – Andy Thomas May 17 '13 at 15:30