为什么Python中的3<<1==6?

发布于 2024-09-27 07:44:25 字数 222 浏览 0 评论 0 原文

可能的重复:
位移位绝对初学者指南?

任何人都可以向我解释一下运算符 << ;或>>

Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?

anyone can explain me that operator << or >>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

跨年 2024-10-04 07:44:25

<<>> 运算符是 位移运算符。 <代码>x << 1 将 x 中的所有位向上移动到下一个最高有效位,有效地乘以 2。更一般地,x << n 将位向上移动 n 个位置。要了解此操作的工作原理,最简单的方法是查看 二进制 表示形式:

3         0000011 =  3
3 << 1    0000110 =  6
3 << 2    0001100 = 12
3 << 3    0011000 = 24

类似地, >> 运算符将位向下移动:

58        0111010 = 58
58 >> 1   0011101 = 29
58 >> 2   0001110 = 14
58 >> 3   0000111 = 7
58 >> 4   0000011 = 3
58 >> 5   0000001 = 1
58 >> 6   0000000 = 0

The << and >> operators are bitshift operators. x << 1 shifts all the bits in x up to the next most significant bit, effectively multiplying by 2. More generally, x << n shifts the bits up n positions. To understand how this operation works it is easiest to look at the binary representation:

3         0000011 =  3
3 << 1    0000110 =  6
3 << 2    0001100 = 12
3 << 3    0011000 = 24

Similarly the >> operator shifts the bits down:

58        0111010 = 58
58 >> 1   0011101 = 29
58 >> 2   0001110 = 14
58 >> 3   0000111 = 7
58 >> 4   0000011 = 3
58 >> 5   0000001 = 1
58 >> 6   0000000 = 0
独夜无伴 2024-10-04 07:44:25

3 在二进制中为 11,左移一位为 110,即十进制中的 6。

想想 a << b as a * (2 ** b)

>> 用于右移。想想a>> b as a // (2 ** b)

3, in binary, is 11 and shifted to left one bit is 110, or 6 in decimal.

Think of a << b as a * (2 ** b)

>> is for right-shifting. Think of a >> b as a // (2 ** b)

风为裳 2024-10-04 07:44:25

这是一个位移位,使用移位操作

假设你有一个数字,查看最低位,你有 3:

0 0 1 1

如果你移动它,你会得到 6,或者:

0 1 1 0

It's a bit shift, using a shifting operation.

Say you have a number, and looking at the lowest bits, you have 3:

0 0 1 1

If you shift it, you'll get 6, or:

0 1 1 0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文