1

I have written a function to print the bit out in a byte. This happens by setting the most significant bit to 1 comparing it to the inputbyte and if it is also 1 printing "1" else "0". The comparison byte is then shifted right.

How do I achieve starting with 10000000 and shifting to 01000000 then 00100000...

I believe my problem is caused by promotion to int then recasting but I don't see the solution.

package errorreporting;

public class ErrorReporting {

ErrorReporting() {
}

public static void main(String[] args) {

    ErrorReporting myError = new ErrorReporting();
    byte myByte = 16;
    myError.printByteArray(myByte);

}

public void printByteArray(byte inputByte) {
    // print out 1 or 0
    byte comparison = -128;
    for (int x = 0; x < 8; x++) {
        if ((inputByte & comparison) != 0) {
            System.out.print("1");
        } else {
            System.out.print("0");
        }
        //       System.out.print(" comparison : " + comparison);
        comparison = (byte) (comparison >>> 1);

    }
    System.out.println(" : " + inputByte);
}

}

This post has some info : Java bitshift strangeness

Community
  • 1
  • 1
Zac
  • 2,229
  • 9
  • 33
  • 41

1 Answers1

1

I believe my problem is caused by promotion to int then recasting

Yes, it is a combination of some implicit and explicit casting and sign extension:

  1. All arguments are first promoted to int before the shift operation takes place, see also https://stackoverflow.com/a/3948303/1611055

  2. Due to 1., your unsigned shift operator >>> does not help - it correctly shifts a 0 into the leftmost position, but since the source argument -128 has been promoted to int before the shift is applied (resulting in 0xffffff80), you end up with 0x7fffffc0 after the first shift.

The simplest solution is to use an int for your mask:

int comparison = 0x80;  // -128;

Theoretically, you could also still use a byte for the mask, but then you need to explicitly convert it to an int while discarding the sign bit at the same time, before applying the shift operator, like this:

byte comparison = -128;
...
comparison = (byte)( (((int) comparison) & 0xff) >>> 1);

((int) comparison) & 0xff) assumes that the byte should really be "unsigned" and converts it to the corresponding "unsigned" int value. Then, you can apply the shift operator (>> or >>> does not matter, since we have a positive int value in any case) and cast it back to a byte.

Community
  • 1
  • 1
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • Thanks this works, I find it a bit annoying that Java does this auto promotion to int thing that makes bit wise operators behave not as expected, I wonder why they decided to do it like that. – Zac Mar 14 '13 at 10:26