Java 移位运算符对预存值的作用与对直接值的作用不同

Java shift operator don't works the same with a pre saved value than with the direct value

解决问题后出现:

https://www.hackerrank.com/challenges/flipping-bits/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=miscellaneous

我的解决方案是:

static long flippingBits(long n) {
    long l=0;                       //Have to pre-declare 0, Why?
    return (~l>>>32)&~n;
}

但我想做的是直接在 return 语句中使用 0 而不是在 "long l" 之前声明它,就像这样:

static long flippingBits(long n) {
    return (~0>>>32)&~n;            //Using 0 directly don't works.
}

我也试过带括号但是是一样的。测试后好像直接放0是不能移位的

为什么给我不同的值?

这应该是一个相当容易的修复。
return (~0>>>32)&~n;:零被解释为 int.
类型 要告诉程序它是 long 类型,请编写以下内容:
return (~0L>>>32)&~n;

在相关说明中,短裤和字节的处理方式相似。

byte b =-16; // 1111000
b = (byte)(b>>>1);
System.out.println(b); //prints -8 and not 120

ANDing0xFF 解决了问题

b = -16;
b = (byte)((b&0xFF)>>1);
System.out.println(b); // prints 120 as expected.

原因是b先转成int再移位

换句话说,如果 n 是长整数,为什么不直接使用 ~n 来翻转位,因为这就是所需要的?