0

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. enter image description here

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.

Felipe Gutierrez
  • 525
  • 1
  • 9
  • 20

2 Answers2

2

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.

Justin L
  • 375
  • 2
  • 10
2

<< 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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
tom
  • 21
  • 1
  • 3