Reputation: 93
The method convertToBinary is used to show the 8bit binary number,
public static String convertToBinary(int a){
String binary="";
for(int i=0;i<8;++i){
Integer bit=new Integer(a&1);
binary=bit.toString()+binary;
a>>=1;
}
return binary;
}
public static void main(String[] args) {
int a=-9;
System.out.println(convertBinary(a)); //11110111
System.out.println(convertBinary(0xaaaa)); //10101010
System.out.println(convertBinary(a&0xaaaa)); //10100010
System.out.println(convertBinary((a&0xaaaa)>>1));//01010001
}
The last result prove that the result of a&0xaaaa
is unsigned,can anyone explain why?
Upvotes: 3
Views: 231
Reputation: 200148
a
is an int
and so is the literal a&0xaaaa
. The result of the bitwise-and operation is also int
. It has 32 bits. With
a&0xaaaa
you have masked out all but the lowest few bits from a
. The result is a positive, 32-bit int
value. So by printing out the lowest 8 bits of
(a&0xaaaa)>>1)
all you reveal is the value of the 9th bit in a&0xaaaa
.
Note that the bit mask 0xaaaa
, even with the flawed assumption that it's no wider than the digits used, is still a 16-bit value and you are printing just the lower 8 bits.
Upvotes: 4
Reputation: 64904
The last result does not prove that >>
did an unsigned shift (saying that the value was unsigned is meaningless, values are just a bunch of bits, it's operations that are signed or unsigned).
Since you're only printing 8 bits, and so not looking at the 24 high bits, you have not seen the only bit that could be affected by the difference between x >> 1
and x >>> 1
, which is the highest bit. There wouldn't have been any difference between a signed shift and an unsigned shift, so based on that result you can not say which happened.
Upvotes: 0