JavaScript | operator [duplicate] - javascript

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
Anyone able to explain what "|" and the value after does? I know the output for 0 creates sets of 13, the numbers, 3, 2, 1, 0. But what about | 1, or | 2.
var i = 52;
while(i--) {
alert(i/13 | 0);
}

It is the bitwise OR operator. There is both an explanation and an example over at MDC. Since doing bitwise OR with one operand being 0 produces the value of the other operand, in this case it does exactly nothing rounds the result of the division down.
If it were written | 1 what it would do is always print odd numbers (because it would set the 1-bit to on); specifically, it would cause even numbers to be incremented by 1 while leaving odd numbers untouched.
Update: As the commenters correctly state, the bitwise operator causes both operands to be treated as integers, therefore removing any fraction of the division result. I stand corrected.

This is a clever way of accomplishing the same effect as:
Math.floor(i/13);
JavaScript developers seem to be good at these kinds of things :)
In JavaScript, all numbers are floating point. There is no integer type. So even when you do:
var i = 1;
i is really the floating point number 1.0. So if you just did i/13, you'd end up with a fractional portion of it, and the output would be 3.846... for example.
When using the bitwise or operator in JavaScript, the runtime has to convert the operands to 32 bit integers before it can proceed. Doing this chops away the fractional part, leaving you with just an integer left behind. Bitwise or of zero is a no op (well, a no op in a language that has true integers) but has the side effect of flooring in JavaScript.

It's a bitwise operator. Specifically the OR Bitwise Operator.
What it basically does is use your var as an array of bits and each corresponding bit is with eachother. The result is 1 if any of them is 1. And 0 if both are 0.
Example:
24 = 11000
10 = 1010
The two aren't of equal length so we pad with 0's
24 = 11000
10 = 01010
26 = 11010
24 | 10 = 26
Best way to learn this is to readup on it.

That is the bitwise OR. In evaluating the expression, the LHS is truncated to an integer and returned, so | is effecively the same as Math.floor().

Related

Why does 100 >> 100 and 100 >>> 100 return 6 in Javascript? [duplicate]

This question already has answers here:
Javascript's Shift right with zero-fill operator (>>>) yielding unexpected result
(2 answers)
Closed 1 year ago.
From the documentation:
The right shift operator (>>) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
From what I understand, since 100 is 0b1100100, shifting it 100 times to the right should yield 0b0. However, when I run 100 >> 100 in Javascript (using chrome), it returns 6. Why is this the case? I am guessing it has something to do with JS's internal representation of numbers but would like to know more clearly.
Edit: The answer is still 6, even when using the unsigned >>> operator. Sign/unsigned does not seem to matter.
Unsigned operation documentation:
The unsigned right shift operator (>>>) (zero-fill right shift) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
The value to the right is taken mod 32. (i.e. Only the last five bits are used.) If you calculate 100>>32, you get 100, which is the same thing you get when you compute 100>>0. After that, 100>>33 is 50, and the cycle repeats.

Javascript 32 bit numbers and the operators & and >>>

I am trying to understand Javascript logical operators and came across 2 statements with seeminlgy similar functionality and trying to understand the difference. So, What's the difference between these 2 lines of code in Javascript?
For a number x,
x >>>= 0;
x &= 0x7fffffff;
If I understand it correctly, they both should give unsigned 32 bit output. However, for same negative value of x (i.e. most significant bit always 1 in both case), I get different outputs, what am I missing?
Thanks
To truncate a number to 32 bits, the simplest and most common method is to use the "|" bit-wise operator:
x |= 0;
JavaScript always considers the result of any 32-bit computation to be negative if the highest bit (bit 31) is set. Don't let that bother you. And don't clear bit 31 in an attempt to make it positive; that incorrectly alters the value.
To convert a negative 32-bit number as a positive value (a value in the range 0 to 4294967295), you can do this:
x = x < 0? x + 0x100000000 : x;
By adding a 33-bit value, automatic sign-extension of bit 31 is inhibited. However, the result is now outside the signed 32-bit range.
Another (tidier) solution is to use the unsigned right-shift operator with a zero shift count:
x >>>= 0;
Technically, all JavaScript numbers are 64-bit floating-point values, but in reality, as long as you keep numbers within the signed 32-bit range, you make it possible for JavaScript runtimes to optimize your code using 32-bit integer operations.
Be aware that when you convert a negative 32-bit value to a positive value using either of above methods, you have essentially produced a 33-bit value, which may defeat any 32-bit optimizations your JavaScript engine uses.

How does ~~ work as math.floor? [duplicate]

This question already has answers here:
What does ~~ ("double tilde") do in Javascript?
(12 answers)
`Math.trunc` vs `|0` vs `<<0` vs `>>0` vs `&-1` vs `^0`
(2 answers)
Closed 8 years ago.
I understand that ~ is a bitwise NOT operator, but how does inverting the bits on a number twice make it function as Math.floor
What does ~~ ("double tilde") do in Javascript? describes the differences between using Math.floor vs bitwise operations to round numbers in Javascript, but I am interested in how exactly inverting the bits twice accomplishes this.
Thanks
~ forces the operand to get cast to an integer. It's a trick to work around the fact that Javascript has no direct way of casting between floating point and integer values. In fact, Javascript doesn't officially have an integer-only type, but implementations are likely to use integers internally for performance.
So ~x is the bitwise inverse of castToInt(x). Then you inverse the bits again to get just castToInt(x).
It happens that casting floating point numbers to integer behaves almost like Math.floor. The most notable difference is that casting rounds towards zero, while Math.floor rounds towards negative infinity. There are some other differences as well:
js> ~~(-4.5)
-4
js> Math.floor(-4.5)
-5
js> ~~Infinity
0
js> Math.floor(Infinity)
Infinity
js> ~~NaN
0
js> Math.floor(NaN)
NaN
js> Math.floor(1e12)
1000000000000
js> ~~1e12
-727379968 // <- be aware of integer overflows!
From the spec, Bitwise NOT, ~
Let expr be the result of evaluating UnaryExpression.
Let oldValue be ToInt32(GetValue(expr)).
Return the result of applying bitwise complement to oldValue. The result is a signed 32-bit integer.
Definition of ToInt32 here.
The "complement" of a 32-bit integer i is i XOR 0xFFFFFFFF.
So put this all together and you have ~~i as meaning
ToInt32(i) XOR 0xFFFFFFFF XOR 0xFFFFFFFF
// same as
ToInt32(i) XOR 0x00000000
// same as
ToInt32(i)
Keep in mind the differences in rounding direction for negative numbers.
Personally I prefer using x | 0 over ~~x because it involves fewer operations for the same result.
It's essentially the equivalent of a truncate function (in the sense that it is casting the float into an integer, which does exactly that), which JavaScript does not have. This is why for negative numbers the behavior is actually closer to Math.ceil.

What's the function of the "|" (pipe) operator? [duplicate]

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
I have this line that I copied from another place:
Total += parseFloat($(this).val())|0;
What's the function of the operator |? When I change the number, I get different results.
The | in JavaScript is an integer bitwise OR operator. In that context, it strips off any fractional portion returned by parseFloat. The expression parseFloat($(this).val()) will result in a number with (potentially) a fractional component, but then |0 will convert it to an integer number, OR it with 0 (which means it won't change), and so the overall result is to get a whole number.
So functionally, it truncates the fractional portion off the number. -1.5 becomes -1, and 1.5 becomes 1. This is like Math.floor, but truncating rather than rounding "down" (Math.floor(-1.5) is -2 — the next lowest whole number — rather than -1 as the |0 version gives us).
So perhaps that's why it was used, to chop off (rather than "floor") the fractional portion of the number.
Alternately, it could be a typo. The author of that code might have meant to write this (note || rather than |):
Total += parseFloat($(this).val()) || 0;
That defends against the possibility that $(this).val() returns "" or similar, resulting in parseFloat returning NaN. It uses the curiously-powerful || operator to return 0 rather than NaN in that case. (And there's an advertisement for putting spaces around your operators.) Would have to know the context of the code to say whether truncating to a whole number (|) makes sense when adding to Total, or if they were just defending the NaN case.
The | operator in javascript is the bitwise or operator
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
This operator treats the operands as 32 bit integers and for every bit returns 1 if either is 1 and 0 otherwise.

">>1" equals "/2"? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
>> in javascript
Here:
var num=10;
console.log(num/2);
num=4;
console.log(num/2);
It gives me 5 and 2.
And this one:
var num=10;
console.log(num>>1);
num=4;
console.log(num>>1);
It also gives me 5 and 2.
So x/2 is the same as x>>1? But why?
For the same reason that dropping the last digit off a normal (decimal) number is the same as dividing it by 10 (ignoring, of course, any non-integer remainder).
In computers, integers are internally represented in binary (base 2). So each digit represents a power of 2 instead of a power of 10 that we're used to with the decimal system.
>> 1 just means to shift all the bits right by one, which is another way of saying "drop the last digit". Since the digits are in binary, that's equivalent to dividing by the base, which is 2.
Similarly, if you need to divide by any power of 2, you can do so using the right shift operator: To divide by 4, shift by 2; to divide by 8, shift by 3; and so on.
Note that internally, it's often more efficient to do a shift operation instead of a division operation, but any compiler worth its salt will do this optimization for you (so that you don't have to write obfuscated code to get the performance benefit -- generally, you would only use the shift operator when your intention is to manipulate bits directly, and use the division operator when your intention is to do math).
x>>1 is a bit shift, which operates on the number's binary representation. The effect is that x>>n is the same as x/(2^n) (except that bit shift is usually faster than division, as it is lower level).
When you >> something, you basically shift all its bits to the right.
When that happens, you shift the 2-place value into the 1-place value, and the 4-place value into the 2-place value, and so on.
This effectively divides a number in half.
Take the number 14, for example:
1110.
When you shift the bits, you get 111, or 7.
Take a look at this:
http://en.wikipedia.org/wiki/Division_by_two#Binary
Everything you need to know about >> can be found here and here.

Categories

Resources