I have this statement:
Assume the bit value of byte
x
is 00101011. what is the result ofx>>2
?
How can I program it and can someone explain me what is doing?
The signed right shift operator '>>' uses the sign bit to fill the trailing positions. For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions. In Java, negative numbers are stored as 2's complement.
The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator " >>> " shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
The left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by << . As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.
The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With