Amit Shinde
Amit Shinde

Reputation: 49

How store values greater than 127 in byte datatype in java

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.

Upvotes: 3

Views: 1794

Answers (3)

Eugen
Eugen

Reputation: 917

For this reason use int or long.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234815

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.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140504

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

Upvotes: 8

Related Questions