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.

8
  • 4
    Don't store them in a byte. Use short or int. Commented May 30, 2018 at 6:44
  • Well, I guess you shouldn't use a byte :P Commented May 30, 2018 at 6:44
  • You are storing in int and typecasting it to byte. This is what you will get. Commented May 30, 2018 at 6:44
  • 1
    @Vishva Dave, I want to write bytes on a BLE device. So can not convert it to short or int. Commented May 30, 2018 at 6:51
  • 1
    Possible duplicate of Java code To convert byte to Hexadecimal Commented May 30, 2018 at 6:53

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

For this reason use int or long.

1 Comment

this is more a comment rather than an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.