我在提取二进制表示的最后 4 个数字时遇到问题
我的号码是:1111 1001
我得到了第一个 4
但是我在获取最后四个时遇到问题^:
# include <stdio.h>
# include <stdlib.h>
# define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d\n"
# define BYTETOBINARY(byte) \
(byte & 0x80 ? 1 : 0), \
(byte & 0x40 ? 1 : 0), \
(byte & 0x20 ? 1 : 0), \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
int main()
{
int num = 505;
PRINTBIN (num);
// int result = num & bitwise;
//PRINTBIN(result);
// first num;
int i;
int bit=0x01;
int bitwise;
for (i =0;i<4;i++)
{
int bit1=bit<<i;
bitwise = bit1|bit;
}
printf("1:%d\n", bitwise);
PRINTBIN(bitwise);
//second num;
int bitwise1;
int b0 = 0;
int bit2;
for(i=0;i<4;i++)
{
bit2 = bit<<(4+i);
bitwise1 = bit2|b0;
PRINTBIN(bit2);
}
printf("2:%d\n",bitwise1);
PRINTBIN(bitwise1);
return 0;
}
最佳答案
有一个比你正在做的更简单的方法:num & 0x0f
会得到最后四个,然后你只需用 printf("%04b\n", num &0x0f);
以二进制形式打印它。编辑: %b 说明符是非标准的!那么可能不应该使用它,而是使用下面的示例。/编辑
任何 f
十六进制为 1111
二进制形式,这使得提取这些四重奏变得很容易。如果您不能只使用 printf,您还可以通过一次屏蔽一个数字,然后移动数字以排列另一个数字来显示,从而非常轻松地打印一些内容。例如:
for(int i = 0; i < 4; i++) {
printf("%c", (number & 8) ? '1' : '0'); // print the number on the left of the quartet
number <<= 1; // shift it to the right by one position, putting the next bit in position to print next loop around
}
位操作中的其他有用技巧是移动一位以获得掩码。要获取位 #n,从右侧开始,执行 number & (1 << n)
。左移零次就是 1 - 该掩码为您提供最不重要(最右边)的位。左移一次就是 2,即第二个最低有效位,依此类推。您的bit1 = bit << i
line 可以做到这一点,但我更喜欢使用文字 1
通过这个技巧可以清楚地表明它不必是变量。
关于c - 提取 int 二进制表示的最后四位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263467/