理解位操作时出错
ERROR in understanding bit-wise operations
我有unsigned int(32位),并希望分为3组,每个组短12位。然而,我无法正确地提取这些数字。例如,假设我有32位unsigned int,如下所示:
1111 0000 1011 0000 1010 1001 1100 1101
那么我想要这样写:
S1 = 1111 0000 1011
s2 = 0000 1010 1001
s3 = 1100 1101
计划:
#include<stdio.h>
int main() {
short s1,s2,s3 = 0
unsigned int addr = 4194624;
s1 = addr>>12;
addr = addr>>12;
printf("%dn", s1);
s2 = addr>>12;
addr = addr>>12;
printf("%dn", s2);
s3 = addr>>12;
addr = addr>>12;
printf("%dn", s3);
return 0;
}
这对我很有用。
// Just pick up the last 8 bits of addr and
// assign it to s3.
s3 = addr & 0xFF;
// Shift addr by 8 bits to the right, then pick up
// just the last 12 bits of the resulting number, and then
// assign it to s2.
s2 = (addr >> 8) & 0xFFF;
// Shift addr by 20 bits to the right and then assign
// the resulting number to s1.
s1 = (addr >> 20);
您可以使用这样的函数来提取位:
short f( unsigned int number, int start, int end)
{
unsigned int mask = (1 << (end - start)) - 1;
return ( number >> start) & mask;
}
:
int main() {
short s1,s2,s3 = 0;
unsigned int addr = 4194624;
s1 = f( addr, 20, 31);
s2 = f( addr, 8, 19);
s3 = f( addr, 0, 7);
printf("%dn", s1);
printf("%dn", s2);
printf("%dn", s3);
return 0;
}
打印:4
1 64年http://ideone.com/Q5mV94复制自注释 -看到你有一个32位的数字首先我做的是将它存储在另一个变量中然后右移20位所以我的新数字是一个12位的数字然后在其他两个12位链上进行相同的操作以获得所需的数字
#includde<stdio.h>
#include<conio.h>
void main()
{
unsigned long a=4194624,e;
int b,c,d;
e=a;
e=e>>20;
b=e;
e=a;
e=e<<12;
e=e>>20;
c=e;
e=a;
e=e<<24;
e=e>>24;
d=e;
printf(" %d %d %d ",b,c,d);
getch();
}
相关文章:
- 对字符串进行位操作
- 对字符数组中的元素执行逐位操作
- 逐位操作的隐式类型转换
- 如何进行特定的位操作?
- C++避免位操作完全移位
- 使用双包装器类进行位操作(C++、clang)修复性能下降问题
- 使用位操作优化检查
- 子集相关位操作
- 使用 c++ 提升库的按位操作
- 位操作和异或
- 位操作将最左侧的设置位转换为右侧交替位?
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- POD 类型的原子按位操作
- 如何使用位操作在单个整数中编码和解码两个数字
- __int128的位操作
- 使用位操作会影响内存消耗?
- 在具有位操作的函数中获得值
- C/C 位操作不会导致预期输出
- 在数组大小中使用位操作的原因
- 理解位操作时出错