-1

I was trying to store byte value in a variable and trying to perform some logic based upon this calculation.

byte mByteValue = -129;   // Holding byte value

Problem is I am always getting value 127, due to which my logic fails everytime.

Any specific reason behind this, why its behaving strange in my case?

pb2q
  • 58,613
  • 19
  • 146
  • 147
Saurabh
  • 975
  • 2
  • 12
  • 27

3 Answers3

3

A byte in java is a signed 8-bit value. 8 bits gives you 256 possible values, but since a byte is signed and can represent positive and negative values, those 256 values must be roughly split in half across the possible positive and negative values. So you can't store negative values past -128; in particular don't expect to be able to store -256.

What you're actually observing when your byte has the value 127 is known as overflow (see this wiki article)

If you need to manipulate values outside this range, as in your example code, or e.g. an unsigned byte, at some point you'll need to make use of a wider integer type, like short.

The standard libraries provide these limits as Byte.MIN_VALUE and Byte.MAX_VALUE (docs here and here).

pb2q
  • 58,613
  • 19
  • 146
  • 147
0

The range of byte is from -128 to 127. You can not store any value beyond these range.

This is because byte is 8 bits. So the maximum positive number stored at byte is -

2^7 -1 = 127. // since the first bit is sing bit; 0 for positive

And minimum negative number stored at byte is-

2^7 = -128 //since the first bit is sign bit; 1 for negative.

And if you use unsigned byte the it would be 255.

Razib
  • 10,965
  • 11
  • 53
  • 80
0

To correctly convert a byte to an int use mByteValue & 0xFF. You can read more about the Two's complement here: https://en.wikipedia.org/wiki/Two%27s_complement.

chris
  • 1,685
  • 3
  • 18
  • 28