什么'x<< 〜y'代表JavaScript? [英] What does 'x << ~y' represent in JavaScript?

查看:98
本文介绍了什么'x<< 〜y'代表JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'x<< 〜y'代表JavaScript?

What does 'x << ~y' represent in JavaScript?

我理解按位 SHIFT 操作会这样做:

I understand that the bitwise SHIFT operation does this:

x << y AS x * 2y

并且波浪号运算符确实:

And a tilde ~ operator does:

~x AS -(x+1)

因此,我假设以下内容:

So, I assume the following:

5 << ~3 AS 5 * 2-4 or 5 * Math.pow(2, -4)

它应该导致 0.3125

但是,当我运行 5<< 〜3 它导致 1342177280

But, when I run 5 << ~3 it results in 1342177280.

一步一步是什么说明?这种操作组合如何以及为什么导致 1342177280 而不是 0.3125

What is a step-by-step explanation? How and why does this combination of operations result in 1342177280 instead of 0.3125?

(此问题类似于Stack 溢出问题 什么是按位运算符? 关于按位 SHIFT 运算符。)

(This question is similar to Stack Overflow question What are bitwise operators? about the bitwise SHIFT operator.)

推荐答案

x<< -n 等于 x<< (32 - n)

~3 == -4 所以

5<< ~3 === 5<< (32-4) === 5<< 28 这是 1,342,177,280

x << -n is equal to x << (32 - n)
~3 == -4 so
5 << ~3 === 5 << (32 - 4) === 5 << 28 which is 1,342,177,280


准确X << -n与X<<< (32-n)...实际上它既简单又复杂......位移位运算符的有效范围是0到31 ...位移运算符中的RHS首先转换为无符号32位整数,然后用31(十六进制1f)掩盖(二进制 11111



                   3 = 00000000000000000000000000000011  
                  ~3 = 11111111111111111111111111111100
       0x1f (the mask) 00000000000000000000000000011111
                       --------------------------------
            ~3 & 0x1f  00000000000000000000000000011100 = 28

当幅度小于32时,它与我上面发布的完全相同虽然

when the magnitude is less than 32, it's exactly the same as what I posted above though

位操作使用32位整数。负位移是没有意义的,因此被包含在正32位整数中

Bit operations work with 32 bit integers. Negative bit shifts are meaningless so are wrapped into positive 32 bit integers

如何<<运算符工作

rhs转换为无符号32位整数 - 如此处所述ToUInt32

The rhs is converted to an unsigned 32bit integer - like explained here ToUInt32

ToUint32基本上取一个数字并返回模数2 ^ 32

ToUint32 basically takes a number and returns the number modulo 2^32

这篇关于什么'x&lt;&lt; 〜y'代表JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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