在Javascript中无符号整数 [英] Unsigned Integer in Javascript

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

问题描述

我的工作是处理IP地址信息的页面上,但它呛上整数签署的事实。我使用的位运算符加快步伐,但第64位(符号/无符号标志)是搞乱起来。

有没有办法来强制Javascript被无符号的一个数字?它似乎做工精细,直到子网超过30大于2,或更小。

试试这个:

 < HTML和GT;
<身体GT;<脚本类型=文/ JavaScript的'>
的document.write((1 <<;小于30)+&所述峰; br /&gt;中);
的document.write((1 <<;&下; 31)+&所述峰; br /&gt;中);
的document.write((1 <<;&下; 32)+&所述峰; br /&gt;中);
&LT; / SCRIPT&GT;&LT; /身体GT;
&LT; / HTML&GT;

结果:


  

1073741824
  -2147483648
  1



解决方案

 的document.write((1 <<;&LT; 31)+&LT; BR /&gt;中);

&LT;&LT; 运算符定义为符号的32位整数(从双precision浮动的本地号码存储转换)工作。因此, 1 LT;&。31 必须产生一个负数

唯一的JavaScript运营商使用32位无符号整数,工程是&GT;&GT;&GT; 。你可以利用这个转换有符号整数,在数您一直在努力与其他位运算符无符号整数式号码:

 的document.write(((1 <<;&LT; 31)&GT;&GT;&GT; 0)+'&LT; BR /&GT;');

同时

 的document.write((1 <<;&LT; 32)+&LT; BR /&gt;中);

将无法工作,因为所有的移位操作仅使用移位的最低5位(JavaScript和其他类似C语言中也是如此)。 &LT;&LT; 32 等于&LT;&LT; 0 ,即得。没有任何变化。

I'm working on a page that processes IP address information, but it's choking on the fact that integers are signed. I am using bitwise operators to speed it up, but the 64th bit (signed/unsigned flag) is messing it up.

Is there any way to force a number to be unsigned in Javascript? It seems to work fine, until subnet is greater than 30, or less than 2.

Try this:

<html>
<body>

<script type='text/javascript'>
document.write( (1 << 30) +"<br/>");
document.write( (1 << 31) +"<br/>");
document.write( (1 << 32) +"<br/>");
</script>

</body>
</html>

Result:

1073741824 -2147483648 1

解决方案

document.write( (1 << 31) +"<br/>");

The << operator is defined as working on signed 32-bit integers (converted from the native Number storage of double-precision float). So 1<<31 must result in a negative number.

The only JavaScript operator that works using unsigned 32-bit integers is >>>. You can exploit this to convert a signed-integer-in-Number you've been working on with the other bitwise operators to an unsigned-integer-in-Number:

document.write(( (1<<31)>>>0 )+'<br />');

Meanwhile:

document.write( (1 << 32) +"<br/>");

won't work because all shift operations use only the lowest 5 bits of shift (in JavaScript and other C-like languages too). <<32 is equal to <<0, ie. no change.

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

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