长整数的按位移位

长整数的按位移位

本文介绍了JavaScript:长整数的按位移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JavaScript中按位移位值64次。但是JavaScript在 32 之后开始四舍五入。

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

例如:

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

这打印来自 0 1073741824 然后轮次并开始打印 0

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

推荐答案

在Java中,按位运算符使用整数.JavaScript没有整数。它只有双精度浮点数。因此,按位运算符转换它们的数字将操作数转换成整数,做生意,然后将它们转换回来。在大多数语言中,这些操作符非常接近硬件而且速度非常快。在JavaScript中,它们离硬件很远而且非常慢.JavaScript很少用于做有点操纵。 - Douglas Crockford,

"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

关键是你没有任何理由使用按位运算符。只需乘以或除以2 ^ numbits。

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

您的代码应为:

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

或者通常:

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

你明白了。

这篇关于JavaScript:长整数的按位移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:30