大整数位操作 [英] Bitwise operations with big integers

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

问题描述

我实现BER-COM pressed整数解码和最近我发现,位运算大整数与一个奇怪的JavaScript行为。

I am implementing decoding of BER-compressed integers and recently I've found a weird JavaScript behavior related to bitwise operations with big integers.

例如:

var a = 17516032;          // has 25 bits
alert(a << 7)              // outputs -2052915200
alert(a * 128)             // outputs  2242052096
alert(2242052096 >> 16)    // outputs -31325
alert(2242052096 / 65536)  // outputs  34211

虽然第一种解决方法(乘法代替左移)是可以接受的,第二个是不

While the first workaround (multiplication instead of left shift) is acceptable, the second isn't.

为什么会发生?如何使用它受得了?

Why it happens? How to bear with it?

推荐答案

17516032 二进制是 00000001000010110100011000000000 。左移7为您提供了 10000101101000110000000000000000 。这是等于 -2052915200 补(这是所有计算机如何重新差不多present负数)。

17516032 in binary is 00000001000010110100011000000000. Shifting to the left by 7 gives you 10000101101000110000000000000000. This is equal to -2052915200 in two's complement (which is how almost all computers represent negative numbers).

&GT;&GT; 是有符号右移。这意味着,在最左边的位(确定数的符号)将被移入的左侧。

>> is a signed right shift. That means that the leftmost bit (which determines the sign of a number) will be shifted into the left side.

例如

1100 >> 2 == 1111
0111 >> 2 == 0001

如果你想要做一个无符号的转变(而忽略符号位),使用&GT;&GT;&GT; 这将填零位串的左端

If you want to do an unsigned shift (which ignores the sign bit), use >>> which will zero-fill the left end of the bitstring.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆