〜JavaScript中的按位运算符 [英] ~ bitwise operator in JavaScript

查看:56
本文介绍了〜JavaScript中的按位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

var a = parseInt('010001',2);
console.log(a.toString(2));
//  10001
var b = ~a;
console.log(b.toString(2));
// -10010

MSDN说

〜在每个位上执行NOT运算符.不产生倒数的值(又称一个人的补语).

~ Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a.

010001 应该返回此 101110 .

此主题还可以确认

所以我不明白我们怎么能得到 -10010 ?唯一可能的解释是:

So I can't understand how we can get -10010 instead ? The only potential explanation is that:

010001被否定101110,但他写下了-10001然后出于一个晦涩的原因,他给了我两个补语和-10001变成-10010.

010001 is negated 101110 but he write this -10001 and then for an obscure reason he give me the two complements and -10001 become -10010.

但是,在我看来,这一切都是很模糊的,您能否对确切发生的事情有所了解.

But all this is very obscure in my mind, would you have an idea on what happen precisely.

推荐答案

在幕后,当Javascript执行按位运算时,它将转换为32位带符号整数表示形式,并使用该整数表示形式,然后将结果转换回其内部小数表示.

Under the covers, when Javascript does bitwise operations, it converts to a 32-bit signed integer representation, and uses that, then converts the result back into its internal decimal representation.

这样,您的输入值 010001 变为 00000000 00000000 00000000 00010001 .

As such, your input value, 010001 becomes 00000000 00000000 00000000 00010001.

然后将其反转:

~00000000 00000000 00000000 00010001 => 11111111 11111111 11111111 11101110

转换为十六进制,转换后的值为 0xFFFFFFEE ,相当于十进制值-18.

Converted into hex, the inverted value is 0xFFFFFFEE, which is equivalent to the decimal value of -18.

由于这是一个值为18的有符号整数,因此该值将被Javascript转换为-18的基础十进制表示形式.

Since this is a signed integer with a value of -18, this value is converted to the underlying decimal representation of -18 by Javascript.

当Javascript尝试将其打印为以2为底的数字时,它会看到负号和18的值,并将其打印为 -10010 ,因为 10010 是正18的二进制表示形式.

When Javascript tries to print it as a base-2 number, it sees the negative sign and the value of 18, and prints it as -10010, since 10010 is the binary representation of positive 18.

这篇关于〜JavaScript中的按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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