2

I'm dealing with converting floats from CCS, which does not follow the IEEE standard (instead of Sign Bit, Exponent, Mantissa, they use Exponent, Sign Bit, Mantissa); I've come across some weird behavior using the >>> operator.

given

byte byte1=(byte)0x8A;     //10001010
byte byte2=(byte)(byte1>>>1);       //11000101

Since >>> specifies that it will insert a 0 , why am I getting a 1?

I can code around this and just manually flip the bit, but I don't want to wind up discovering it is platform specific.

Sheriff
  • 495
  • 4
  • 16
  • Adding `0x` before a number tells the JVM it's a hex value (in this case do `0x8A`), and is simpler than `Byte.decode` :) EDIT: In fact, Byte.decode won't work there... – Alex Coleman Oct 02 '12 at 20:57
  • @AlexColeman true, and good point. In this case I'm not actually doing so, just used it for the example's purpose. The REAL `Byte` I am receiving already has thte `8A` in it. Thank you. – Sheriff Oct 02 '12 at 20:59
  • You gotta cast to byte too (It is an int) ;) But ok – Alex Coleman Oct 02 '12 at 20:59

3 Answers3

2

In java, bytes are cast to ints automatically before the shift operates on them. Codologically, what you're doing is equivalent to:

byte byte2=(byte)(((int)byte1)>>>1);

And, of course, casting to int sign extends. If you were to leave the result as an integer, you would see the (then) expected value of 0x7FFFFFC5.

To get around this, just mask the 8th bit flat.

byte byte2 = (byte) (byte1 >>> 1 & 0x7F);

Related question

Isn't this behavior sensible and expected and isn't java great?

Community
  • 1
  • 1
Wug
  • 12,956
  • 4
  • 34
  • 54
1

Don't use bytes, stick with int's. However, running the following code:

    int int1 = 0x8A;
    System.out.println(formatBinary(int1));
    int int2 = int1 >>> 1;
    System.out.println(formatBinary(int2));

gets me this output (with a formatting printing method called formatBinary which is irrelevant):

8a: 10001010
45: 01000101
Alex Coleman
  • 7,216
  • 1
  • 22
  • 31
0

You're using ints, not bytes. The int values must have more 1 bits above the 8th that you're shifting in.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • removed the `int` altogether, all `byte`s. Still the same results. The bitshift appears to return a `int` regardless, so I had to cast as a `byte`. – Sheriff Oct 02 '12 at 20:53