Bitwise differences in Java / Perl
I fiddled around and noticed differences that I don't understand between Java and Perl when I shifted the -1 bit.
I thought that integers are stored in binary binary, so if there are 32 bits, -1 equals 11 ... 11 (32 times).
I would expect -1 → 1 to give $ 2 ^ 31 - 1 $ = 011 ... 11 = 2147483647.
I would expect -1 <<1 to give = 11 ... 110 = -2.
What is the reason for these different behaviors and where are these standards specified in different languages?
Code and printouts for Perl and Java below:
In Perl:
print (-1 >> 1, "\n");
print (-1 << 1, "\n");
2147483647
4294967294
In Java:
public class Tempy {
public static void main(String[] args){
System.out.println( -1 >> 1);
System.out.println( -1 << 1);
}
}
-1
-2
source to share
Perl's bit wrap is inherently unsigned, so -1 is treated as 2 ^ 32 -1, and it is automatically filled with 0, so -1 >> 1
equal to 2 ^ 31-1 and -1 << 1
equal to 2 ^ 32-2.
[Edit] Thanks @Powerlord, using integer
will force perl to use signed values.
The Java bit shift sign expands (if used >>
), so it -1 << 1
is still -1 and -1 >> 1
equal to -2. If you don't want to sign the extension, you need to use the boolean version >>>
.
source to share