1

I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set.

To keep this readable, I declare some flags like this:

private static final byte FLAG_A   = 0b00010000;
private static final byte FLAG_B   = 0b00100000;
private static final byte FLAG_C   = 0b00011000;

That works perfectly.

The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me)

private static final byte FLAG_D   = 0b10000000;

Any idea what's going on?

Joeri Hendrickx
  • 15,619
  • 4
  • 37
  • 53
  • `... = (byte) 0b10000000;` is the easiest solution; so int 128 becomes byte -128. (Java byte is signed -128..127, numeric overflows discarded) – Joop Eggen May 11 '16 at 07:28

4 Answers4

4

0bxxxx notation is for bit-wise representation of integers, which can be cast to byte if they fit, but this is not special byte-only notation. 0b1000000 is positive +128, which is more than can fit into byte. You would need to do something like -0b111111 (-127) to achieve byte pattern 0b1000000, but it is probably better to do explicit cast. What you are really looking for is unsigned byte type, which java lacks.

Artur Biesiadowski
  • 3,419
  • 2
  • 11
  • 18
1

Taking it from where @Artur Biesiadowski left off, you are in essence attempting to store more than a byte can handle.

 1    0    0    0    0    0    0    0
7th  6th  5th  4th  3rd  2nd  1st  0th

This value is +128; Java byte range is -128 to +127 [read further here].

A cleaner and more readable way could be to use hex instead of the 0bxxx.

Now, since you are asking to store +128 in a datatype that can store a maximum of +127, it is automatically using a datatype that can store a greater range, i.e., int via a process of type promotion. [JLS 5.x] explains this in great detail.

Community
  • 1
  • 1
Debosmit Ray
  • 4,731
  • 2
  • 21
  • 41
0

An alternative solution is to use a BitSet with its more human readable methods. You can still use flags for the individual bits, but they'd be indexes instead of bitmasks. Then you can just retrieve the resulting byte with BitSet.toByteArray()[0].

Kayaman
  • 67,952
  • 3
  • 69
  • 110
-3

You may want to declare your flag as

private static final unsigned byte

I guess the compiler thinks the 255 is not fitting in to an signed byte (which only holdes -128 to 127)

SaschaZorn
  • 134
  • 1
  • 2