I am trying to understand the command "someByte << 2" in java. For what is it for? At the iscsi docmentation there is a caching mode page saying about DEMAND READ RETENTION PRIORITY and WRITE RETENTION PRIORIRY.
at the source there is this code for these messages:
// serialize byte 3
b = (byte)((demandReadRetentionPriority << 4) | writeRetentionPriority);
buffer.put(b);
Why do they use "<< 4" command with demandReadRetentionPriority and not with writeRetentionPriority? And what does << means in that case?
Thanks.
You can see from the documentation that the demandReadRetentionPriority is in the upper 4 bits (bits 7,6,5, and 4) of the byte and writeRetentionPriority is stored in the lower 4 bits (3,2,1, and 0) of the byte.
The code you provided is simply shifting the value stored in the demandReadRetentionPriority variable to the upper 4 bits. The << is a bit shift operation.
For example, if the value of demandReadRetentionPriority were 1 then it would be shifted 4 bits and the byte would have a binary representation as follows:
00010000
And in order for one of the lower bits of b to be set to 1, the corresponding bit in writeRetentionPolicy would have to also be set to 1, since the lower 4 bits of demandReadRetentionPolicy will be 0 after the bit shift.
<< is the "Signed left shift" operator, a bit shifting operator.
Example:
You have stored the number 279 that would be 100010111 in decimal. When you shift 4 steps to the left you get 1000101110000 (2224) because it will "move" the decimal number to the left and fill the spaces with zeroes.
100010111 << 4
=> 1000101110000
++++
Shifting operations are very fast because they are usually implemented in the hardware as a single machine instruction.
| is also an operator on the bit-level: The bitwise inclusive OR.
Summary of operators in java
Related
public int getRGB(Object inData) {
return (getAlpha(inData) << 24)
| (getRed(inData) << 16)
| (getGreen(inData) << 8)
| (getBlue(inData) << 0);
}
So, what does this return statement actually do? Four ints are shifted, but what is returned?
It returns an int whose first (MSB) byte is the Alpha value, its 2nd byte is the Red value, its 3rd byte is the Green value and its last byte is the Blue value.
highest lowest
bit bit
|--------|--------|--------|--------|
Alpha Red Green Blue
(8 bits) (8 bits) (8 bits) (8 bits)
What you get is the following :
Alpha | Red | Green | Blue - an 32 bit ARGB value - 8 bits for each. As you can see, alpha is shifted 24 bits to the left (leftmost - most significant bits), after which comes the red, with 8 bits, thus placing red in second first 8 bits and masking the remaining 16. Afterward, green is shifted with 8 bits, masking the last byte and finally, blue is put in its place.
| is bitwise OR with strict evaluation, in contrast to ||, which may stop evaluation of the statements in the condition as soon as one expression returns true. But these methods (presumably) return integers, so in Java you (to my knowledge) cannot test these against true directly anyway. No problem since that is not what you are doing - you are shifting the individual results from the methods, filling up new bits with 0 and cutting off the old ones. What this achieves is to pack the (presumably) at most byte-sized, positive values (0 to 255) in one of the 4 bytes which make up an integer. Essentially this is packing 4 pieces of information which require one byte each into one variable of type integer. The type of the target variable could be anything, as long as it has enough bytes to store the information, but it gets more sloppy and questionable from there.
thank you in advance for this basic question.
I am going through a tutorial and I see this line.
int a = (n & 8) / 8
This is supposed to identify whether the fourth bit from the right is a binary representation of 0 or 1. I understand the concept of bits etc, but I do not understand what mathematical equation (if any) this represents.
Would anyone care to explain how this would be written in a mathematical equation? Also, please let me know if i am missing anything else in my understanding of this line. Thank you.
The expression ( n & 8 )
does Logical And of n with 1000 binary.
So that gets the 4th bit from right.
then dividing that by 8, shifts the value right 3 binary places. I.e. it moves the 4th bit to the rightmost place.
That is more clearly expressed as " >> 3"
So your overall expression would be something like:
(n AND 1000 ) >> 3
And that leaves the 4th bit of N in a temporary variable, as bit 0 (rightmost bit).
All the other bits will be zero because of the AND.
8 in decimal is 1000 in binary
so if you do bitwise AND with any number
n & 8
it will stay 8 only if the 4th bit is 1 and
if you divide it by 8 again it will return 1, zero otherwise
For example
for 9 (1001)
9 & 8
would be
1001
& 1000
------
1000
Now for the case where forth bit is 0
for 7 (0111)
7 & 8
would be
0111
& 1000
-----
0000
int a = (n & 8) / 8;
The n & 8 applys a logical AND mask to the 4th bit of n;
n: 11001010 // example value
8: 00001000
result: 00001000
Dividing that number by 8 brings the result to the lowest bit :
result: 00000001
Dividing a number by 2^n shifts the numbers n bits to the right (in the same way that multiplying by 2^n shifts bits to the left).
The result is assigned to variable a, which now contains 0 or 1, depending on the value of the 4th bit.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
a&b=0000 1100
then a&b is also an integer which is further divided by 8 in your example.
I am working on a small project. During the searching on google I see some code in java .
int red = (pixel >> 16) & 0x000000FF;
But I do not understand what is the meaning of that ? CAn anybody explain summary of that logical operation ? I read that it is shifted sth like that but shift of what ?
The red component of a color is stored as a number between 0-255, but "packed" into an integer. Here's my ASCII art, in binary, 32 bits per integer, showing the 8 bits each for Alpha,Red,Green,and Blue. Read the bit number vertically! I'm numbering from 1, not 0. (Also, you can argue that the numbers go the wrong direction - they are there just to help you count!)
11111111112222222222333
12345678901234567890123456789012
AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB the pixel value
The pixel >> 16 will shift the result right by 16 bits. In effect, this removes the G and B stuff
AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB move everything 16 to the right, this becomes
----------------AAAAAAAARRRRRRRR
where the - depends on sign. You can look it up but in this case it doesn't matter.
So, you have your Red number, almost. There is still the Alpha component, all that AA.... If you mask ("and") with 0xFF, which is the lowest 8 bits
----------------AAAAAAAARRRRRRRR (result of the bit shift)
00000000000000000000000011111111 (0xFF)
you get
000000000000000000000000RRRRRRRR
which is the result desired, a number between 0 and 255.
This is a bitwise "AND" operator. When it is applied to the number FF (hex) it clears all bits of an int except the final 8.
Recall that bitwise "AND" goes through a binary representation of a number, and puts ones in the result only in positions where both operands have ones. Since a 32-bit mask containing FF looks like this in binary
00000000000000000000000011111111
the upper three bytes of the result are going to be zeros. The last byte, where FF has all ones, will be equal to the last byte of the first operand.
& - bitwise AND operator
>> - right shift operator - shifts a bit pattern to the right
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
For example
4 in binary 100, if you do >>1 that would be 010 which is 2
8 in binary 1000, if you do >>1 that would be 0100 which is 4
See also
What are bitwise shift (bit-shift) operators and how do they work?
This code segment:
(x >>> 3) & ((1 << 5) - 1)
apparently results in a 5-bit integer with bits 3 - 7 of x.
How would you go about understanding this?
Let's look at ((1 << 5) - 1) first.
1 << 5 is equal to 100000 in binary.
When we subtract 1, we're left with 11111, a binary number of five 1s.
Now, it's important to understand that a & 0b11111 is an operation that keeps only the 5 least significant bits of a. Recall that the & of two bits is 1 if and only if both of the bits are 1. Any bits in a above the 5th bit, therefore, will become 0, since bit & 0 == 0. Moreover, all of the bits from bit 1 to bit 5 will retain their original value, since bit & 1 == bit (0 & 1 == 0 and 1 & 1 == 1).
Now, because we shift the bits of x in x >>> 3 down by 3, losing the three least significant bits of x, we are applying the process above to bits 4 to 8 (starting at index 1). Hence, the result of the operation retains only those bits (if we say the first bit is bit 0, then that would indeed be bit 3 to bit 7, as you've stated).
Let's take an example: 1234. In binary, that's 10011010010. So, we start with the shift by 3:
10011010010 >>> 3 = 10011010
Essentially we just trim off the last 3 bits. Now we can perform the & operation:
10011010
& 00011111
--------
00011010
So, our final result is 11010. As you can see, the result is as expected:
bits | 1 0 0 1 1 0 1 0 0 1 0
index | 10 9 8 7 6 5 4 3 2 1 0
^-------^
(x >>> 3)
Shifts x right 3 bits logically, i.e. not sign-extending at the left. The lower-order 3 bits are lost. (This is equivalent to an unsigned division by 8.)
1 << 5
Shifts 1 left 5 bits, i.e. multiplies it by 32, yielding 0b00000000000000000000000000100000.
-1
Subtracts one from that, giving 31, or 0b00000000000000000000000000011111.
&
ANDs these together, yielding only the lower-order 5 bits of the result of x >>> 3, in other words bits 3..7 of the original x.
"How would you go about understanding this?".
I assume that you are actually asking how you should go about understanding it. (As distinct from someone just explaining it to you ...)
The way to understand it is to "hand execute" it.
Get a piece of paper and a pencil.
Based on your understanding of how Java operator precedence works, figure out the order in which the operations will be performed.
Based on your understanding of each operator, write the input patterns of bits on the piece of paper and "hand execute" each operation ... in the correct order.
If you do this a few times with a few values of x, you should get to understand why this expression gives you a 5 bit number.
If you repeat this exercise for a few other examples, you should get to the point where you don't need to go through the tedious process of working it out with a pencil and paper.
I see that #arshajii has essentially done this for you for this example. But I think you will get a deeper understanding if you do / repeat the work for yourself.
One thing to remember about integer and bitwise operations in Java is that the operations are always performed using 32 or 64 bit operations ... even if the operands are 8 or 16 bit. Another thing to remember (though it is not relevant here) is that the right hand operand of a shift operator is chopped to 5 or 6 bits, depending on whether this is a 32 or 64 bit operation.
I have a simple question - I need to write a function for my program to change the 3rd bit of a given byte.
I wrote those lines :
public byte turnOn(Byte value)
{
int flag = 8;
value = (byte) (value | flag);
return value;
}
I'm not sure if it's the right way to do that, because I saw also this way (with which I am unfamiliar)
value = (byte) (value | (1 << 2) );
which way is better, and what does 1 << 2 means (2 means the third bit, but what is the 1 )
Thanks!
1 << 2 means 1 shifted two bits to the left. Since shifting left by one bit is similar to multiplying by two, this gives 4. In binary, this is
00000100
i.e. the 3rd bit from the right is set.
The constant 1 is used since that number only has a single bit set - the rightmost bit. After shifting left, only the 3rd bit (from the right) is set:
00000001 original value
00000010 after shifting left once
00000100 after shifting left again
I prefer using 1 << 2 instead of a constant like 8, as it makes it clearer which bit is being set. It also prevents you inadvertently using a constant that has multiple bits set - unless you actually want that, of course. Even then, it's clearer in my opinion to add together several bits, for clarity:
final int bitsToSet = (1 << 2) + (1 << 5);
4 (or 1 << 2) is 00000100 in binary¹. ORing with this mask sets the third least significant bit (or the fifth significant bit in a byte).
8 (or 1 << 3) is 00001000 in binary, so you're setting the fourth least significant bit (or the fifth one of a byte).
It does not matter which expression you use, the shifting just makes it clear you're using a bitmask. Alternatively, you can use the hexadecimal 0x04 which is (imho) easier to translate to the binary bitmask.
1 The leading zeros do not change the value, but should simplify counting the position of the set bit in a byte.
(1 << 2) will left-shift the value 1 twice. Generically, (x << y) means x * (2 ^ y). So 1 << 2 is 4.
Generally speaking, it should not matter whether you use the bit-shift or bit-set method. The compiler should optimize either way.
That said, are you looking for the 3rd bit, indexed from 0 or indexed from 1? If you're looking for the third-right-most bit starting at index 1, you want your flag to be 4 instead of 8. Additionally, the | operator is the set-value operator. If you literally want to "change" the bit, you want to use the ^ operator -- bitwise XOR -- which is the toggle-value operator.
Does that make sense?