I have this statement:
Assume the bit value of byte x is 00101011. what is the result of x>>2
how can I program it and can someone explain me what is doing?
Bye and thanks for answering
I have this statement:
Assume the bit value of byte x is 00101011. what is the result of x>>2
how can I program it and can someone explain me what is doing?
Bye and thanks for answering
When you shift right 2 bits you drop the 2 least significant bits. So:
x = 00101011
x >> 2
// now (notice the 2 new 0's on the left of the byte)
x = 00001010
This is essentially the same thing as dividing an int by 2, 2 times.
In Java
byte b = (byte) 16;
b = b >> 2;
// prints 4
System.out.println(b);
You can't write binary literals like 00101011
in Java so you can write it in hexadecimal instead:
byte x = 0x2b;
To calculate the result of x >> 2
you can then just write exactly that and print the result.
System.out.println(x >> 2);
>>
is the Arithmetic Right Shift operator. All of the bits in the first operand are shifted the number of places indicated by the second operand. The leftmost bits in the result are set to the same value as the leftmost bit in the original number. (This is so that negative numbers remain negative.)
Here's your specific case:
00101011
001010 <-- Shifted twice to the right (rightmost bits dropped)
00001010 <-- Leftmost bits filled with 0s (to match leftmost bit in original number)
Firstly, you can not shift a byte
in java, you can only shift an int
or a long
. So the byte
will undergo promotion first, e.g.
00101011
-> 00000000000000000000000000101011
or
11010100
-> 11111111111111111111111111010100
Now, x >> N
means (if you view it as a string of binary digits):
00000000000000000000000000101011 >> 2
-> 00000000000000000000000000001010
11111111111111111111111111010100 >> 2
-> 11111111111111111111111111110101
byte x = 51; //00101011
byte y = (byte) (x >> 2); //00001010 aka Base(10) 10
public class Shift {
public static void main(String[] args) {
Byte b = Byte.parseByte("00101011",2);
System.out.println(b);
byte val = b.byteValue();
Byte shifted = new Byte((byte) (val >> 2));
System.out.println(shifted);
// often overloked are the methods of Integer
int i = Integer.parseInt("00101011",2);
System.out.println( Integer.toBinaryString(i));
i >>= 2;
System.out.println( Integer.toBinaryString(i));
}
}
Output:
43
10
101011
1010
You can use e.g. this API if you would like to see bitString presentation of your numbers. Uncommons Math