Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bitwise operators in javascript

Tags:

javascript

I am creating a bitmask in javascript. It works fine for bit 0 through 14. When I set only bit fifteen to 1. It yields the integer value of "-2147483648" instead of "2147483648". I can do a special case hack here by returning hardcoded "2147483648" for bit fifteen but I would like to know the correct way of doing it.

Sample code:

function join_bitmap(hex_lower_word, hex_upper_word)
{
    var lower_word = parseInt(hex_lower_word, 16);
    var upper_word = parseInt(hex_upper_word, 16);
    return (0x00000000ffffffff & ((upper_word<<16) | lower_word));
}

Above code returns -2147483648 when hex_lower_word is "0x0" and hex_upper_word is "0x8000" instead of 2147483648

like image 285
F Yaqoob Avatar asked Feb 04 '13 19:02

F Yaqoob


People also ask

Can you do bitwise operations in JavaScript?

JavaScript Uses 32 bits Bitwise Operands JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.

How bitwise and works in JavaScript?

JavaScript Bitwise ANDBitwise AND & returns 1 if the corresponding bits of both operands are 1 else it returns 0. Let's take a look at the bitwise AND operation of two integers 12 and 25. Note: Converting 12 to 32-bit binary gives us 00000000000000000000000000001100 and 25 gives 00000000000000000000000000011001 .

What is the use of bitwise operator?

A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits. Bitwise operators are used in: Communication stacks where the individual bits in the header attached to the data signify important information.

What does XOR do in JavaScript?

The bitwise XOR operator ( ^ ) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1 s.


1 Answers

The reason for this is because Javascript's bit shift operations use signed 32-bit integers. So if you do this:

0x1 << 31   // sets the 15th bit of the high word

It will set the sign bit to 1, which means negative.

On the other hand instead of bit shifting you multiply by powers of two, you'll get the result you want:

1 * Math.pow(2, 31)
like image 123
robbrit Avatar answered Oct 08 '22 07:10

robbrit