What do “>>” and “

These are the shift right (with sign) and shift left operators.

Essentially, these operators are used to manipulate values at BIT-level.
They are typically used along with the the & (bitwise AND) and | (bitwise OR) operators and in association with masks values such as the 0x7F and similar immediate values found the question’s snippet.
The snippet in question uses these operators to “parse” the three components of a 32 bits float value (sign, exponent and fraction).

For example, in the question’s snippet:
1 - (2*(b1 >> 7)) produces the integer value 1 or -1 depending if the bit 7 (the 8th bit from the right) in the b1 variable is zero or one respectively.
This idiom can be explained as follow.

  • at the start, b1, expressed as bits is 0000000000000000abcdefgh
    note how all the bits on the left are zeros, this comes from the
    b1 = data.charCodeAt(offset) & 0xFF assignement a few lines above, which essentially zero-ed all the bits in b1 except for the rightmot 8 bits (0xFF mask).
    a, b, c… thru h represent unknown boolean values either 0 or 1.
    We are interested in testing the value of a.
  • b1 >> 7 shifts this value to the right by 7 bits, leaving
    b1 as 00000000000000000000000a which, read as an integer will have value 1 or 0
  • this 1 or 0 integer value is then multiplied by 2
    it is then either 2 or 0, respectively.
  • this value is then substracted from 1, leaving either -1 or 1.

Although useful to illustrate the way the bit-operators work, the above idiom could be replaced by something which tests the bit 7 more directly and assigns the sign variable more explicitly. Furthermore this approach does not require the initial masking of the leftmost bits in b1:

var sign
if (b1 & 0x80)   // test bit 7  (0x80 is  [00000000]10000000)
  sign = -1;
else
  sign = 1;

Leave a Comment