I understand what is Zero-fill right shift and results it yields make perfect sense when second operand is non-zero:
-7 >>> 1
2147483644
Compare with
-7 >> 1
-4
But when second operand is zero:
-7 >> 0
-7 // Looks right!
-7 >>> 0
4294967289 // What? Why?
If I'm shifting zero bits, doesn't it mean I'm not shifting at all? If that's the case, shouldn't it give me back the original number? I would expect -7 >>> 0 === -7
And also
-7 >>> 32
4294967289
Again, by definition, I would expect -7 >>> n === 0 where n >= 32 because all digits become zeros!
Found the internal workings of it in specs.
x >>> 0 will do ToUint32(x)
And
7.1.6 ToUint32 ( argument )
The abstract operation ToUint32 converts argument to one of 232
integer values in the range 0 through 232−1, inclusive. This abstract
operation functions as follows: Let number be ToNumber(argument).
ReturnIfAbrupt(number). If number is NaN, +0, −0, +∞, or −∞, return
+0. Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(number)). Let int32bit be int modulo
232. Return int32bit.
Note Let int32bit be int modulo, and
The notation “x modulo y” (y must be finite and nonzero) computes a
value k of the same sign as y (or zero) such that abs(k) < abs(y) and
x−k = q × y for some integer q.
So by above convention, -7 mod 2^32 === 2^32 - 7 === 4294967289
Related
Why
9 >> 2 = 2
and
-9 >> 2 = -3
?
I mean, why not -2.
From the bitwise operators page on MDN -
"The operands of all bitwise operators are converted to signed 32-bit integers in big-endian order and in two's complement format. Big-endian order means that the most significant bit (the bit position with the greatest value) is the left-most bit if the 32 bits are arranged in a horizontal line. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. one's complement of the number) plus one."
1001 (9) >> 2 = 10 (2)
2's compliment 9 to get -9 and do the same:
0111 (-9) >> 2 = 01
2's compliment the result and you get 11 or 3, so the answer is -3
-1 = 11111111
-2 = 11111110
-3 = 11111101
-4 = 11111100
..
-8 = 11111000
-9 = 11110111
thus
-9 >> 2 = -3
Citing the ECMAScript spec Section 5.2:
The notation “x modulo y” (y must be finite and nonzero) computes a
value k of the same sign as y (or zero) such that abs(k) < abs(y) and
x−k = q × y for some integer q.
so if y is positive, the result k of 'x modulo y' is positive regardless of the sign of x.
and if my understanding is right, ToInt32(-1) equals ToInt32(1)?
The notation x modulo y is used internally within the spec to describe the result of certain operations. So yes, the result k of x modulo y is (by definition) of the same sign as y. It is not claimed that the % operator is equivalent to modulo.
If you're interested, the actual spec for % can be found under section 11.5.3. Interestingly, it makes no use of modulo.
Copy pasting from my previous answer here:
Take a % b
1. When both +ve, Modulo & Remainder are one and the same
2. When a is -ve, they are not the same
For example;
a = -10, b = 3
Remainder of -10 % 3 = -1
for Modulo, add a greater multiple of 3 to your 'a' and calculate the remainder.
-10 + 12 = 2
2 % 3 = 2 is your answer
The modulo operation is defined as the mathematical modulo operation:
Mathematical operations such as addition, subtraction, negation,
multiplication, division, and the mathematical functions defined later
in this clause should always be understood as computing exact
mathematical results on mathematical real numbers, which do not
include infinities and do not include a negative zero that is
distinguished from positive zero.
Your question:
ToInt32(-1) equals ToInt32(1)
Well, no:
Let posInt be sign(number) * floor(abs(number)).
posInt = sign(-1) * floor(abs(-1)) = -1;
Let int32bit be posInt modulo 232; that is, a finite integer value k
of Number type with positive sign and less than 232 in magnitude such
that the mathematical difference of posInt and k is mathematically an
integer multiple of 232.
int32bit = posInt mod 4294967296 = -1 mod 4294967296 = 4294967295
(wolfram alpha link for mathematical result)
If int32bit is greater than or equal to 231, return int32bit − 232,
otherwise return int32bit.
Because 4294967295 >= 2147483648, we return 4294967295 - 4294967296, I.E. -1.
If we run the same steps for ToInt32(1), we get 1. So they don't have the same result.
I have this code. Please make me understand what does this code actually mean
for(var i = 0; i < input.length; i++)
{
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt( x & 0x0F);
}
What is 0x0F? And, >>> Mean?
>>> is the unsigned bitwise right-shift operator. 0x0F is a hexadecimal number which equals 15 in decimal. It represents the lower four bits and translates the the bit-pattern 0000 1111. & is a bitwise AND operation.
(x >>> 4) & 0x0F gives you the upper nibble of a byte. So if you have 6A, you basically end up with 06:
6A = ((0110 1010 >>> 4) & 0x0F) = (0000 0110 & 0x0F) = (0000 0110 & 0000 1111) = 0000 0110 = 06
x & 0x0F gives you the lower nibble of the byte. So if you have 6A, you end up with 0A.
6A = (0110 1010 & 0x0F) = (0110 1010 & 0000 1111) = 0000 1010 = 0A
From what I can tell, it looks like it is summing up the values of the individual nibbles of all characters in a string, perhaps to create a checksum of some sort.
0x0f is a hexadecimal representation of a byte. Specifically, the bit pattern 00001111
It's taking the value of the character, shifting it 4 places to the right (>>> 4, it's an unsigned shift) and then performing a bit-wise AND with the pattern above - eg ignoring the left-most 4 bits resulting in a number 0-15.
Then it adds that number to the original character's right-most 4 bits (the 2nd & 0x0F without a shift), another 0-15 number.
0x0F is a number in hexadecimal. And >>> is the bitwise right-shift operator.
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 '>')
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;
These are bit operators. Have a look at this link: Bitwise Operators
You can read about the operators here: https://developer.mozilla.org/en/JavaScript/Reference/operators/bitwise_operators
They are bit shifts and also occur in languages other than JS.
Example: 5 >> 1 = 2
binary: 0101 shifting one position = 0010
It is an arithmetic shift
Right and Left and shift operators.
shift a by b bits to the left (padding with zeros)
a << b
shift a by b bits to the right (copying the sign bit)
a >> b
From http://ecma262-5.com/ELS5_HTML.htm
11.7 Bitwise Shift Operators
ShiftExpression :
AdditiveExpression
ShiftExpression << AdditiveExpression
ShiftExpression >> AdditiveExpression
ShiftExpression >>> AdditiveExpression
11.7.1 The Left Shift Operator ( << )
Performs a bitwise left shift operation on the left operand by the amount specified by the right operand.
The production ShiftExpression : ShiftExpression << AdditiveExpression is evaluated as follows:
Let lref be the result of evaluating ShiftExpression.
Let lval be GetValue(lref).
Let rref be the result of evaluating AdditiveExpression.
Let rval be GetValue(rref).
Let lnum be ToInt32(lval).
Let rnum be ToUint32(rval).
Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
Return the result of left shifting lnum by shiftCount bits. The result is a signed 32-bit integer.
11.7.2 The Signed Right Shift Operator ( >> )
Performs a sign-filling bitwise right shift operation on the left operand by the amount specified by the right operand.
The production ShiftExpression : ShiftExpression >> AdditiveExpression is evaluated as follows:
Let lref be the result of evaluating ShiftExpression.
Let lval be GetValue(lref).
Let rref be the result of evaluating AdditiveExpression.
Let rval be GetValue(rref).
Let lnum be ToInt32(lval).
Let rnum be ToUint32(rval).
Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
Return the result of performing a sign-extending right shift of lnum by shiftCount bits. The most significant bit is propagated. The result is a signed 32-bit integer.
shift left and shift right operators. If you have a number it will shift its bits to left or right.
It's the bitshifting operator. See here for more details.
They are bitshift operators. Numbers in the computer are represented in binary. Shifting left is equivalent to multiplying by 2 and shifting right is equivalent to dividing by 2.
For example, the number 8 is 1000 in binary. Shift left << by 3 would yield 1000000 which is 64. Shift right by 2 would yield 10 which is 2.
console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1
Why does 0.5 | 0 return zero, but any integer (including negative) returns the input integer? What does the single pipe ("|") do?
This is a bitwise or.
Since bitwise operations only make sense on integers, 0.5 is truncated.
x | 0 is x, if x is an integer.
Bit comparison is so simple it's almost incomprehensible ;) Check out this "nybble"
8 4 2 1
-------
0 1 1 0 = 6 (4 + 2)
1 0 1 0 = 10 (8 + 2)
=======
1 1 1 0 = 14 (8 + 4 + 2)
Bitwise ORing 6 and 10 will give you 14:
alert(6 | 10); // should show 14
Terribly confusing!
A single pipe is a bit-wise OR.
Performs the OR operation on each pair
of bits. a OR b yields 1 if either a
or b is 1.
JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0, which is 0.
This example will help you.
var testPipe = function(input) {
console.log('input => ' + input);
console.log('single pipe | => ' + (input | 'fallback'));
console.log('double pipe || => ' + (input || 'fallback'));
console.log('-------------------------');
};
testPipe();
testPipe('something');
testPipe(50);
testPipe(0);
testPipe(-1);
testPipe(true);
testPipe(false);
This is a Bitwsie OR (|).
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded.
So, in our case decimal number is converted to interger 0.5 to 0.
= 0.5 | 0
= 0 | 0
= 0