处理JavaScript中的二进制/位移位

处理JavaScript中的二进制/位移位,javascript,binary,bit-manipulation,Javascript,Binary,Bit Manipulation,我试图在JavaScript中执行一些位移位操作和处理二进制数 这就是我要做的。用户输入一个值,我使用它执行以下操作: // Square Input and mod with 65536 to keep it below that value var squaredInput = (inputVal * inputVal) % 65536; // Figure out how many bits is the squared input number var bits = Math.floor

我试图在JavaScript中执行一些位移位操作和处理二进制数

这就是我要做的。用户输入一个值,我使用它执行以下操作:

// Square Input and mod with 65536 to keep it below that value
var squaredInput = (inputVal * inputVal) % 65536;
// Figure out how many bits is the squared input number
var bits = Math.floor(Math.log(squaredInput) / Math.log(2)) + 1;
// Convert that number to a 16-bit number using bitshift.
var squaredShifted = squaredInput >>> (16 - bits);
只要这个数字大于46,它就可以工作。一旦低于46,它就不起作用。 我知道问题是位移位。现在来自C背景,我知道这将是不同的做法,因为所有数字都将以32位格式存储(假设它是
int
)。JavaScript是否也这样做(因为它
var
s没有被键入)

如果是,是否可以存储16位数字?如果不是,我是否可以将其视为32位,并进行所需的计算以假定它是16位

注意:我试图在
squaredInput
中提取16位值的中间4位

另一个注意事项:当打印出var时,它只打印出没有填充的值,所以我无法计算出来。尝试使用
parseInt
toString


谢谢你在找这个吗

function get16bitnumber( inputVal ){
   return ("0000000000000000"+(inputVal * inputVal).toString(2)).substr(-16);
}

此函数返回
(inputVal*inputVal)
值的最后16位。通过使用二进制字符串,您可以使用任意范围的位。

如果不一定要使用,请不要在JS中使用位移位。这本书至少提到了四种数字格式

  • IEEE 754
  • Int32
  • UInt32
  • UInt16
知道什么时候用哪个真的很困惑

例如,
~
在转换为Int32时应用位反转。UInt16似乎仅在
字符串中使用。fromCharCode
。使用位移位运算符将操作数转换为UInt32或Int32

在您的情况下,右换档操作符
>
。 你打字的时候

a >>> b
这就是你得到的:

ToUInt32(a) >>> (ToUInt32(b) & 0x1f)

试试
(squaredInput>>16)&0xffff
我还想建议一个位掩码,我发现它们很有用。在JavaScript中,所有数字都是64位浮点。仅在处理时,它们将被转换为32位有符号整数。@Pointy仍然会产生相同的问题。46岁以下的都不起作用。我怎样才能用空格打印出
squaredInput
?那么整个存储的数字。为什么在开头放16个0?用于填充
get16bitnumber
将始终返回长度为16的二进制字符串,带前导字符zeros@Nayefc我已经更新了我的答案,这可能对你有用。