Compare only specific bits of a number - javascript

I am trying to do a comparison between two numbers, however I only want that the n-th bit of one of the numbers to be equal a certain binary value
ex: assert (5==0b1XX) == true
since 5 is 0b101 and the 3rd MSB is 1
Is there anyway I can use a don't care (X) in javascript?

Use bitwise SHIFT >> along with bitwise AND & to achieve this.
// SHIFT off the first two bits, then check the first bit with AND
(0b101 >> 2 & 1) === 1
>> will shift bits to the right and discard any bits shifted off.
& will return a 1 when the corresponding bits are both 1.
Here is the MDN page on bitwise operators.
Here is a function you can use for any value in any position:
// returns true if 'target' has a 'value' at 'position'
function checkBit(target, position, value) {
return (target >> (position - 1) & 1) === value;
}

#hermbit is right. I'll take a shot at explaining it too.
You can shift the bit representation of a number by using the >> operator.
So if you have the number 5 0b101 and you shift it two places you get 0b001 (removed last two places and filled left side with 0s.
Then you can use the & to make a logical and of both numbers. In this case
0b001 & 0b001 is equal to 0b001, because it will return a number where the bits will be 1 only in the places where both numbers are 1.
I hope this clarifies things.

Related

Result of -1%7 is different in javascript(-1) and python(6)

The expression -1 % 7 in JavaScript is giving me -1 as the result. Whereas in Python and Haskell, I found the result to be 6.
Can anyone explain why both have different behaviors? Which one is correct?
I'm going to give a slightly different answer. As others have said, functions can do whatever you define them to and m - x = -x mod m. As a prelude, I'll note that Haskell has two "mod" functions, mod and rem which differ in just this aspect. You can make a case that the mod one is preferable mathematically. The rem one corresponds to what you'd get on an x86 processor. There is, in fact, a third one, the Euclidean one, which may be even better as well as described by Raymond Boute in The Euclidean Definitions of the Functions Div and Mod. The third form always returns a positive modulus. (There are, in fact, at least two other choices that can be made.)
So, Javascript's definition is what you get from most machine mod opcodes. In this sense, it might be preferable as this would make it more efficient to implement. Mathematically, Haskell's and Python's definition is better than Javascript's. There's also a third definition which may be slightly better.
One key property that the Euclidean and Haskell/Python definitions both possess is x mod m = y mod m is equivalent to x = y mod m which Javascript's definition lacks. You can verify by calculating 6 % 7 in Javascript.
Both are correct. Some languages return positive modulo numbers, while others retain their sign.
You can simply add the modulus to your variable to get a positive number, or check if the number is positive or negative before performing the modulus operation and correct the result after to switch between the two.
Pseudocode to convert a%b between the two:
In a language where -1%7 == -1, you do this to get a positive number:
((a%b)+b) % b
And in a language where -1%7 == 6 you can do this to get the signed version:
if a < 0:
return (a%b)-b
else:
return a%b
Both are correct, they just use different conventions regarding the handling of negative operands. For positive numbers, the conventions coincide, but for negative numbers they do not. In Python a % b always has the same sign as b.
In what follows, I'll use Python notation, where // is used for integer division.
Let
q, r = a // b, a % b
Then
a == q * b + r
must be true in any language (assuming a and b are integers, with b not equal to zero). So the way the remainder is handled has to be consistent with the convention used for integer division. In Python, integer division is floor division, i.e., the result is rounded towards negative infinity. In some other languages rounding towards zero is used instead. And in some languages, you get whatever convention the CPU manufacturer decided to implement, so the same code run on different hardware can give different results. As you can imagine, that can be somewhat annoying. :)
The % stands for different operators in JavaScript and in Python.
In JavaScript, the % stands for the Remainder operator. The documentation already points out the difference between the remainder and the modulo operation:
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
(Emphasis by me)
In contrast to that: In Python, the % stands for the modulo operator. The documentation also makes a statement about the sign:
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. [...] The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
(Emphasis by me)
Both are correct.
To complete the other answers, you can also consider the divmod function in Python:
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
>>> divmod(-1, 7)
(-1, 6)

Math.random and arithmetic shift

If I have the following code in JavaScript:
var index1 = (Math.random() * 6) >> 0;
var index2 = Math.floor(Math.random() * 6);
The results for index1 or index2 are anywhere between 0 and 6.
I must be confused with my understanding of the >> operator. I thought that by using arithmetic shift that the results for index1 would be anywhere between 1 and 6.
I am noticing, however that I don't need to use Math.floor() or Math.round() for index1 if I use the >> operator.
I know I can achieve this by adding 1 to both indexes, but I was hoping there was a better way of ensuring results are from 1 to 6 instead of adding 1.
I'm aware that bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
UPDATE:
I saw the original usage in this CAAT tutorial on line 26 and was wondering whether that would actually return a random number between 1 and 6 and it seems it would only ever return a random number between 0 and 6. So you would never actually see the anim1.png fish image!
Thank you in advance for any enlightenment.
Wikipedia says '(Arithmetic right shifts for negative numbers would be equivalent to division using rounding towards 0 in one's complement representation of signed numbers as was used by some historic computers.)'
Not exactly an answer, but the idea is that >> 0 is really specific and shouldn't be used in general for getting a range between 1 and 6.
Most people would tell you to do
Math.floor((Math.random()*10)+1);

numbers and toFixed , toPrecision in Javascript?

Regarding the famous issue of 1.01+1.02 which is 2.0300000000000002
one of the workarounds is to use toFixed : e.g.
(1.01+1.02).toFixed(2) --->"2.03"
But I saw a solution with toPrecision
parseFloat((1.01+1.02).toPrecision(10))-->"2.03"
But lets have a look at n in
toFixed(n)
toPrecision(n)
How would I know what is n ?
0.xxxxxxxxxxx
+
0.yyyyyyyyyyyyy
---------------------
0.zzzzzzzzzzzzzzzzzzzzzzzzz
^
|
-----??????------
each number being added can have a different decimal digits...
for example :
1.0002+1.01+1.03333--> 3.0435300000000005
how would I calculate the n here ? what is the best practice for this (specific) issue ?
For addition as in this situation I would check the number of decimal places in each operand.
In the simplest of situations the number of decimal places in the operand with the greatest number of decimal places is the value of n.
Once you have this, use which ever method you like to truncate your value. Then get rid of trailing zeros.
You may encounter trailing zeros in situations such as 1.06 + 1.04, the first step would take you to 1.10 then truncating the zero would give 1.1
In your last example 1.0002+1.01+1.03333 greatest number of decimal places is 5 so you are left with 3.04353 and there are no trailing zeros to truncate.
This returns the expected output:
function add(){
// Initialize output and "length" properties
var length = 0;
var output = 0;
// Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);)
for(var i = 0; i < arguments.length; i++){
// If the current argument's length as string is longer than the previous one (or greater than 0 in case of the first argument))
if(arguments[0].toString().length > length){
// Set the current length to the argument's length (+1 is to account for the decimal point taking 1 character.)
length = arguments[0].toString().length +1;
}
// Add the current character to the output with a precision specified by the longest argument.
output = parseFloat((output+arguments[i]).toPrecision(length));
}
// Do whatever you with with the result, here. Usually, you'd 'return output;'
console.log(output);
}
add(); // Returns 0
add(1,2,3); // Returns 6
add(1.01,2.01,3.03); // Returns 6.05
add(1.01,2.0213,3.3333); // Returns 6.3646
add(11.01,2.0213,31.3333); // Returns 44.3646
parseFloat even gets rid of trailing zero's for you.
This function accepts as many numbers as parameters as you wish, then adds these together taking the numbers' string length into account, when adding them. The precision used in the addition is dynamically modified to fit the "currently added" argument's length.
Fiddle
If you're doing calculations, you have a couple of choices:
multiply the numbers by eg 100, to convert to integers, then do the calculations, then convert back again
do the calculations, dont worry about the rounding errors, then round the result at display time
If you're dealing with money/currencies, the first option is probably not a bad option. If you're just doing scientific maths, I would personally not worry about it, and just round the results at display time, eg to 6 significant figures which is the default for my c++ compiler (gcc; not sure if it is in the c++ standards or not, but if you print 1.234567890 in gcc c++, the output is 1.23457, and the problem is avoided)
var a = 216.57421;
a.toPrecision(1); // => '200' because 216 with 1 < 5;
a.toPrecision(2); // => '220' because 216 with 6 >= 5;
a.toFixed(1); // => 216.6 because 7 >= 5;
a.toFixed(2); // => 216.57 because 4 < 5;

What does ">>" mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do these operators do?
I'm working with some javascript for html 5's canvas. I'm looking at some existing code and I've come across the following:
element.height >> 1
element.width >> 1
Its used as part of some arithmetic.
I am using prototype.js as well, if this helps.
>> is the bitwise shifting operator. So >> 1 basically shifts the binary representation of the number on the left by one to the right. This is equal to an integer division by 2.
So element.height >> 1 equals to Math.floor( element.height / 2)
It's a bitshift operator.
It's a sign-propagating right-shift; full explanation here: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators#.3E.3E_%28Sign-propagating_right_shift%29.
Shifting (bitshift) operator.
1 << 1
This shifts the bitpattern 00000001 to the left once (padding with 0s)- you get 00000010, which is 2.
1 << 2
shifts it by two, so you get 00000100, which is 4.
It comes useful when implementing binary protocols, where only 2 bits can mean something. Using shifting you can strip out the rest.
This is the sign-propagating right shift operator which shifts the digits of the binary representation of the first operand to the right by the number of places specified by the second operand, discarding any shifted off to the right. The copies of the leftmost bit are added on from the left, thereby preserving the sign of the number.
So in your case everything is shifted one place to the right.

Fastest way to create this number?

I'm writing a function to extend a number with sign to a wider bit length. This is a very frequently used action in the PowerPC instruction set. This is what I have so far:
function exts(value, from, to) {
return (value | something_goes_here);
}
value is the integer input, from is the number of bits that the value is using, and to is the target bit length.
What is the most efficient way to create a number that has to - from bits set to 1, followed by from bits set to 0?
Ignoring the fact that JavaScript has no 0b number syntax, for example, if I called
exts(0b1010101010, 10, 14)
I would want the function to OR the value with 0b11110000000000, returning a sign-extended result of 0b11111010101010.
A number containing p one bits followed by q zero bits can be generated via
((1<<p)-1)<<q
thus in your case
((1<<(to-from))-1)<<from
or much shorter
(1<<to)-(1<<from)
if you have the number 2^q (= 1 shifted left by q) represented as an integer of width p + q bits, it has the representation:
0...010...0
p-1 q
then 2^q - 1 has the representation
0...01...1
p q
which is exactly the opposite of you want. So just flip the bits
hence what you want is NOT((1 LEFT SHIFT by q) - 1)
= ~((1 << q) - 1) in c notation
I am not overly familiar with binary mathematics in JavaScript... But if you need to OR a number with 0b11110000000000, then I assume you would just convert that to decimal (which would get you 15360), and do value | 15360.
Relevant info that you may find useful: parseInt("11110000000000", 2) converts a binary number (specified as a string) to a decimal number, and (15360).toString(2) converts a decimal number (15360 in this case) to a binary number (the result is a string).
Revised solution
There's probably a more elegant and mathematical method, but here's a quick-and-dirty solution:
var S = "";
for(var i=0;i<p;i++)
S += "1";
for(i=0;i<q;i++)
S += "0";
S = parseInt(S, 2); // convert to decimal

Categories