简体   繁体   中英

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.

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

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 .

因此使用intlong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM