+ 2
Bit operator >>>
but the bitwise operator >>> shouldn't put 0s in the leftmost bit? instead it propagates the leftmost bit as >>. why? https://code.sololearn.com/c6iPg2Y1F01Y/?ref=app
6 Réponses
+ 2
in the Java Language Specification book for Java SE 16 it is written
"...
The value of n >>> s is n right-shifted s bit positions with zero-extension, where:
• If n is positive, then the result is the same as that of n >> s.
• If n is negative and the type of the left-hand operand is int, then the result is
equal to that of the expression (n >> s) + (2 << ~s).
• If n is negative and the type of the left-hand operand is long, then the result is
equal to that of the expression (n >> s) + (2L << ~s).
..."
so it works properly only on int (short and byte are promoted to int) and long
https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.19
+ 3
I'm guessing it has something to do with the number of bits supported by the `byte` type.
From what I read https://cs-fundamentals.com/java-programming/java-operators-precedence-and-associativity that >>> was meant for "unsigned or zero fill right shift". But IIRC there is no unsigned `byte` in java.
Because the number of usable bits for signed and unsigned type were different, and the fact that `byte` only is 1 byte in size, shifting the bits results in unexpected output (yields -1 instead of 1).
If you use %d for output, you will see -1 (in 8 bits binary => 11111111). If `int` was used rather than `byte`, you will get 1 as result.
+ 3
I can't agree.
A bit operator operates on bits and not on the type of data used. In Java, integer types are prefixed and machine independent. byte 8 bit, short 16 bit, int 32 bit, long 64 bit and they are all signed (two's complement).
From the definition >>> must not propagate the sign bit but insert zeros. So a byte z = -128 (equivalent to 0b1000_000) shifted to the right by 7 bits with >>> must produce 1 while with >> it must produce 255 (0b1111_1111) that is, it propagates the sign.
why isn't it like that? looking and studying I came to the conclusion that the problem is related to the fact that the operator >>> returns and work with int
so int work, long work, byte and short require more attention
+ 1
No problem at all
It's just what I think, I never said it must be right 👌