I have a piece of Javascript code I'm trying to understand
// read big-endian (network byte order) 32-bit float
readFloat32 = function(data, offset) {
var b1 = data.charCodeAt(offset) & 0xFF,
b2 = data.charCodeAt(offset+1) & 0xFF,
b3 = data.charCodeAt(offset+2) & 0xFF,
b4 = data.charCodeAt(offset+3) & 0xFF;
var sign = 1 - (2*(b1 >> 7)); //<--- here it is and 2 lines below
var exp = (((b1 << 1) & 0xff) | (b2 >> 7)) - 127;
var sig = ((b2 & 0x7f) << 16) | (b3 << 8) | b4;
if (sig == 0 && exp == -127)
return 0.0;
return sign * (1 + sig * Math.pow(2, -23)) * Math.pow(2, exp);
}
what does ">>" mean? Is it a special type of boolean (like '<' or '>')
The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.
The >>> operator is identical to the >> operator, except that the bits that fill in the shifted left bits have the value of 0. The >>> operator is said to be an unsigned shift because it does not preserve the sign of the operand.
8) What is the result of Right Shift Operator >> on (00110000>>2).? Explanation: Right Shift Operator shift bits on the right side and fills Zeroes on the left side.
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.
0000000000000000abcdefgh
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).b1 >> 7
shifts this value to the right by 7 bits, leaving00000000000000000000000a
which, read as an integer will have value 1 or 0Although 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;
These are bit operators. Have a look at this link: Bitwise Operators
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