3

How store values greater than 127 in byte datatype in java.

int b = 160;
System.out.println((byte)b);

It prints -96.

Note : I want to write bytes on a BLE device. So can not convert it to short or int.

Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55

3 Answers3

8

You might want to store a value in the range 128-255 in a byte. You can, provided you don't also want to store a value -128 to -1 in the same byte (at a different time, obviously).

Just use the bitwise and operator when you want to read it:

b & 0xff
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

The range of a byte is the inclusive range -128 to +127.

You can't store a number greater than 127 in a byte, although you can abuse the range -128 to -1. Your output -96 is attained since the eight bit pattern of -96 matches 160 written in binary. Crudely, you can recover your original number if you add 256 to any negative, or mask all apart from the final 8 bits using b & 256.

If you want to store 160 then use a char (0 to 65535), a short, or an int.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

For this reason use int or long.

Peanut
  • 3,753
  • 3
  • 31
  • 45
Eugen
  • 877
  • 6
  • 16