C语言 将整数值设置为位掩码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2882276/
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
set integer value as bit mask
提问by Vladimir
What is simplest way to assign a bit mask to integer value? For example I want integer with first, third and forth bits = 1, other = 0.
为整数值分配位掩码的最简单方法是什么?例如,我想要第一、第三和第四位 = 1,其他 = 0 的整数。
Certainly I am looking for code, not for single value! And certainly there lot of possibilities, but I try to find simplest and most descriptive looking
当然,我正在寻找代码,而不是单一价值!当然有很多可能性,但我试图找到最简单和最具描述性的外观
回答by unwind
I think the best way to think (!) is to just index bits from 0, and then apply "to set the n:th bit, bitwise-OR with the value (1 << n)":
我认为思考 (!) 的最佳方法是从 0 开始索引位,然后应用“设置第 n:th 位,与值 (1 << n) 按位或”:
int first_third_and_fourth = (1 << 0) | (1 << 2) | (1 << 3);
回答by paxdiablo
If you want your code to be readable in terms of the bit numbers, something like this may be useful:
如果你希望你的代码在位数方面是可读的,这样的事情可能很有用:
#define b0 0x0001
#define b1 0x0002
#define b2 0x0004
#define b3 0x0008
#define b4 0x0010
:
#define b15 0x8000
int mask = b3|b2|b0;
But, after a while you should be able to tell which hex values relate to which bits and you won't need mnemonic tricks like that:
但是,过了一会儿,您应该能够分辨出哪些十六进制值与哪些位相关,并且您不需要像这样的助记技巧:
int mask = 0x000d;
回答by Brian R. Bondy
Use the OR Bitwise operator (|) to combine bits:
使用 OR 按位运算符 ( |) 组合位:
#define FIRST_BIT (0x1)
#define SECOND_BIT (0x2)
#define THIRD_BIT (0x4)
#define FOURTH_BIT (0x8)
/* Increase by for each bit, *2 each time,
0x prefix means they're specified via a hex value */
int x = FIRST_BIT | THIRD_BIT | FOURTH_BIT;
And you can check if a bit is set using the AND Bitwise operator (&):
您可以使用 AND 按位运算符 ( &)检查是否设置了位:
int isset = x&FIRST_BIT;
回答by Sean Bright
This should do it:
这应该这样做:
int x = 0x0D;
And if you're lucky enough to use gcc and don't need to be portable:
如果你有幸使用 gcc 并且不需要便携:
int x = 0b1101;
回答by catchmeifyoutry
Here is an online bit converter, if you don't want to do the sum yourself:
这是一个在线位转换器,如果您不想自己计算总和:
http://www.binaryconvert.com/convert_unsigned_int.html
http://www.binaryconvert.com/convert_unsigned_int.html
Just fill in the bits below (e.g. 1101), and compute the answer (e.g. 0x0000000D). Any capable calculator should be able to do the same ...
只需填写下面的位(例如 1101),然后计算答案(例如 0x0000000D)。任何有能力的计算器都应该能够做同样的事情......
回答by Puppy
Do
做
int something = 0x00000001 * 2;
until you get to where you want.
直到你到达你想要的地方。

