java bit manipulation

前端 未结 5 1018
日久生厌
日久生厌 2020-12-06 06:24
byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println(\"X: \" + x);
}

As I understand it, java sto

5条回答
  •  余生分开走
    2020-12-06 07:01

    The problem is, as told before (long time ago), that x get upcasted to int (sign-extended) before doing the shift.
    Doing a "bit-to-bit" conversion should help:

    byte x = -1;
    for(int i = 0; i < 8; i++)
    {
        x = (byte) ((x & 0xFF) >>> 1);
        System.out.println("X: " + x);
    }
    

提交回复
热议问题