C语言 屏蔽掉 c 中不需要的位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5177159/
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
masking out unwanted bits in c
提问by foo
Given the decimal 71744474in binary it is 0100010001101011101111011010what I am trying to extract from this decimal is every seven bits starting from the lower bits. Each of the seven bits are to represent a printable ASCII character which can only have 7 bits. In total I am pulling out four characters. The first character is 1011010which is Zin ASCII. The next character is wand so on. I am thinking there is a way to mask out the bits I care about some how.
鉴于71744474二进制十进制,0100010001101011101111011010我试图从这个十进制中提取的是从低位开始每七位。七位中的每一位都代表一个只能有 7 位的可打印 ASCII 字符。我总共拉出四个字符。第一个字符是1011010这是Z在ASCII。下一个字符是w等等。我在想有一种方法可以掩盖我关心的一些方式。
回答by Hari Menon
Use bitwise operators:
使用按位运算符:
0100010001101011101111011010 & 0000000000000000000001111111 = 1011010
To get the second character, do
要获得第二个字符,请执行
0100010001101011101111011010 & 0000000000000011111110000000
and so on..
等等..
回答by paxdiablo
Something along the lines of this should suffice:
类似的东西应该足够了:
#include <stdio.h>
int main (void) {
unsigned int value = 71184592; // Secret key :-)
for (unsigned int shift = 0; shift < 28; shift += 7)
printf ("%c", (value >> shift) & 0x7f);
putchar ('\n');
return 0;
}
It uses bit shifting get the specific bits you want into the least significant seven bits of the value, and bit masking to clear out all other bits.
它使用位移位将您想要的特定位转换为值的最低有效七位,并使用位掩码清除所有其他位。
If you run that code, you'll see it can quite happily extract the individual ASCII characters in groups of seven bits each:
如果您运行该代码,您会看到它可以非常愉快地以 7 位为一组提取单个 ASCII 字符:
Pax!
回答by abelenky
int myN = 71744474;
int mask = 0x7F7F7F7F; // 7F is 0111 1111, or 7 on bits.
int result = myN & mask;
char myBytes[4];
myBytes[0] = (char)((result & 0x000000FF);
myBytes[1] = (char)((result >> 8) & 0x000000FF);
myBytes[2] = (char)((result >> 16) & 0x000000FF);
myBytes[3] = (char)((result >> 24) & 0x000000FF);
// Now, examine myBytes[0-3], and I think they'll be what you want.
回答by CyberDem0n
#include <stdio.h>
int main()
{
int a = 71744474;
a = a&0xFFFFFFF; // 1111111 1111111 1111111 1111111
while (a>0) {
char b = a&0x7f; // 1111111
printf("%c", b);
a = a>>7;
}
}

