C++ (1U << X) 有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2128442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does (1U << X) do?
提问by Karl von Moor
I found this piece of code:
我找到了这段代码:
enum
{
IsDynamic = (1U << 0), // ...
IsSharable = (1U << 1), // ...
IsStrong = (1U << 2) // ...
};
What does the (1U << X)
do?
有什么作用(1U << X)
?
回答by Philippe Leybaert
It sets bitmasks:
它设置位掩码:
1U << 0 = 1
1U << 1 = 2
1U << 2 = 4
etc...
What happens is 1U (unsigned value 1) is shifted to the left by x bits.
发生的情况是 1U(无符号值 1)向左移动 x 位。
The code you posted is equivalent to:
您发布的代码相当于:
enum
{
IsDynamic = 1U, // binary: 00000000000000000000000000000001
IsSharable = 2U, // binary: 00000000000000000000000000000010
IsStrong = 4U // binary: 00000000000000000000000000000100
}
回答by Hamish Grubijan
Bit shift. Instead of saying a = 1, b = 2, c = 4 they shift the bits. The idea is to pack many flags into one integer (or long).
位移。他们不是说 a = 1、b = 2、c = 4,而是移位了这些位。这个想法是将许多标志打包成一个整数(或长整数)。
This is actually a very clean approach.
这实际上是一种非常干净的方法。
回答by Ben Gottlieb
<< is the bitshift operator. It will take the bits in the left side and shift them by an amount specified by the right side. For example:
<< 是位移运算符。它将获取左侧的位并将它们移位右侧指定的数量。例如:
1 << 1 -> 0b0001 << 1 => 0b0010
1 << 2 -> 0b0001 << 2 => 0b0100
etc.
等等。
回答by Mark Ransom
1U
is an unsigned value with the single bit 0 set, and all the other bits cleared. The <<
operator means "shift to the left". 1U << 0
means create a value with bit 0 set; 1U << 1
means create a value with bit 1 set; etc.
1U
是一个无符号值,设置了单个位 0,并且所有其他位都被清除。该<<
运营商表示“左移”。 1U << 0
表示创建一个设置为位 0 的值;1U << 1
表示创建一个设置位 1 的值;等等。
回答by Bill Bingham
That snippet
那个片段
enum
{
IsDynamic = (1U << 0), // ...
IsSharable = (1U << 1), // ...
IsStrong = (1U << 2) // ...
}
declares an enumeration with values which are powers of 2. To be used presumably as masks on a value which contains multiple flags.
声明一个枚举,其值为 2 的幂。大概用作包含多个标志的值的掩码。
So for example a value representing something that IsDynamic and IsSharable is
例如,表示 IsDynamic 和 IsSharable 的值是
unsigned value = IsDynamic | IsSharable; // could use + as well
And to test if the value IsStrong
并测试值是否为 IsStrong
if (value & IsStrong) { ... }