JavaScript: Bitwise shift of long long number

I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after 32.

For example:

for(var j = 0; j < 64; j++)
{
    mask = mask << 1;
    console.log(mask);
}

This prints value from 0 to 1073741824 but then rounds of and starts printing 0.

Answers


"In Java, the bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow. JavaScript is rarely used for doing bit manipulation." - Douglas Crockford, Javascript: The Good Parts

The point is that you don't really have any reason to use bitwise operators. Just multiply or divide by 2^numbits.

Your code should be:

for(var j = 0; j < 64; j++) {
 mask = mask * 2;
 console.log(mask);
}

Or generally:

function lshift(num, bits) {
    return num * Math.pow(2,bits);
}

You get the idea.


Need Your Help

HTML5 web sockets - how to communicate with them?

ruby html5 sockets tcpserver handshaking

I've tested many socket examples and communication between them was pretty simple: socket is opened and stays open until you close it and no information is being sent except the one you have sent.

Set up wcf service for http and https and also add username/password to its access

asp.net wcf service soa

I am kinda new to WCF and the setting up of service and have 2 questions. My first question I have a service that will be accessed via https on a web server. However locally on my local IIS7, it wi...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.