Reputation: 91
public class UnsignedShift {
public static void main(String[] args) {
char hex[] = new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
byte b = (byte) 0xf1;
byte d = (byte)(b>>>4);
System.out.println("b>>>4=0x" + hex[(d>>4)&0x0f] + hex[d&0x0f]);
}
}
The result = 0xff
can anyone explain how it is possible in Java?
I think,it is 0x0f
Upvotes: 1
Views: 528
Reputation: 2949
byte b = (byte) 0xf1 will be 1111 0001
byte d = (byte)(b>>>4) will be 1111 1111
d>>4 will be 11111111
0x0f will be 00001111
(d>>4)&0x0f will be 00001111 == 15
d will be 11111111
0f will be 00001111
hex[d&0x0f] will be 00001111 == 15
So Final Answer : 0xff
I think you are expecting (byte)(b>>>4) to shift 0 from left to right 4 times. But b is an integer with 32 bits, it will move 4 bytes from left but get ignored by (byte) conversion. byte conversion take 8 least significant bits of an integer.
Upvotes: 0
Reputation: 999
There are no binary operators in java that can operate directly with bytes (8 bits). Variables of type byte, short or char automatically suffer a "numeric promotion" to a 32 bit integer before operations like these are performed as detailed in here. So here is what happens in your code:
public static void main(String[] args) {
char hex[] = new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
byte b = (byte) 0xf1; // b is a byte with 0xf1
byte d = (byte)(b>>>4); // b is converted to int, becoming 0xfffffff1 then shifted
// to the right by 4 bits, resulting in 0x0fffffff
System.out.println("b>>>4=0x" + hex[(d>>4)&0x0f] + hex[d&0x0f]);
}
If you want to get that right its just easier to use 32 bit variables for all binary operations, like in the example below:
public static void main(String[] args) {
char hex[] = new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
byte b = (byte) 0xf1;
int ib = b & 0xff;
byte d = (byte)(ib>>>4);
System.out.println("b>>>4=0x" + hex[(d>>4)&0x0f] + hex[d&0x0f]);
}
Note: Just in case you don't know, you can easily print an integer number in the hexadecimal format by calling Integer.toHexString(n)
.
Upvotes: 1