|Written by Ian Elliot|
|Thursday, 11 July 2019|
Page 1 of 3
As you would expect the not operator has the highest priority.
Notice that there are also corresponding logical operators &&, || and ! that only work with Boolean values and not bit patterns.
If you are more familiar with other languages you might well confuse ^ with raise to a power.
The bitwise operators work with numeric data which is converted from floating point to a 32-bit integer, operated on and then converted back to floating point. As a floating double can store a 32-bit integer without loss of precision everything works transparently as long as you stay within the 32-bit limit.
var a = 0xF0;
var b = 0xFF;
var c = ~a & b;
works out Not(a)=0F and b i.e. 0F & FF which is F. You should see the result 15 in decimal displayed.
Notice that bit manipulation is usually easiest to try out using hexadecimal notation e.g. 0xF is 15 in decimal.
So what happens if you go over the 32-bit limit?
In fact strange things start to happen before you reach the 32-bit limit because the 32-bit value is signed and this means that if the highest bit is one the returned value is negative.
var a = 0xFFFFFFF;
var b = 0xFFFFFFF
var c = a & b;
displays 0xFFFFFFF which is what you would expect. Notice that toString(16) converts the floating point number to a hex string.
Now try adding one more F to both values i.e. a full 32-bit value all set to one. The result displays as -1 which might not be what you expect but it is perfectly correct.
The result of anding two full 32-bit values both set to one is a 32-bit value with all bits set to one but as the 32-bit value is interpreted as a signed value this converts to -1 (twos complement).
You don't have to worry about this too much as the bit pattern corresponding to -1 is 32 bits all set to one so everything should carry on working is you use the value for further bit manipulation.
Now consider what happens if you add one more F to the values. In this case the values are 36 bits all set to one and the result should also be 36 bits all set to one - but no.
Both the a and b values are converted to 32-bit values the two values are anded together and the result is a 32-bit result i.e. -1 as before.
Beyond 32 bits
So what happens if you try to work with bitwise operators on values that aren't representable as 32-bit integers?
It ignores all fractional parts by truncation.
If the value is larger than a 32-bit integer can store then the result is 32 bits all set to one i.e. -1 in twos complement.
If the value is a fraction smaller than one then the result is zero.
If the value is infinity (plus or minus) or NaN then the result is zero.
You will also be pleased to learn that true evaluates to one and false to zero so you can use the bitwise logical operators on Boolean values. Just about every other possible value returns 0.