我有两个无符号的int数:a
和b
(b是无符号的int指针)。我想将a
的第8和第9位复制到b
的第2和第3位(所有索引都基于0)。
我就是这样做的:
bool secondBit = (a & (1 << 8) ) ;
bool thirdBit = (a & (1 << 9) ) ;
if (secondBit) {
*b |= (1u << 2);
}
if (thirdBit) {
*b |= (1u << 3);
提醒:b
是无符号的int指针。
有更好的方法吗?
答案 0 :(得分:13)
清除*b
的相关位并将其设置为a
所需的位:
*b = (*b & ~0xC) | ((a & 0x300) >> 6);
// This is the 'not' of 00001100, in other words, 11110011
~0xC;
// This zeros the bits of *b that you do not want (b being a pointer)
*b & ~0xC; // *b & 11110011
//This clears all of a except the bits that you want
a & 0x300;
// Shift the result into the location that you want to set in *b (bits 2 and 3)
((a & 0x300) >> 6);
// Now set the bits into *b without changing any other bits in *b
*b = (*b & ~0xC) | ((a & 0x300) >> 6);
答案 1 :(得分:2)
取决于您对“更好”的定义:)
但是,嗯,C ++中有std::bitset
类。也许它通过提供一个不易出错的界面来满足您的需求。
答案 2 :(得分:0)
在给定的代码中,它不会复制这些位 - 它只是它们。它应该做什么
*b &= ~0xC0;
第一?然后
*b |= ((a >> 6) & 0xC0);
答案 3 :(得分:0)
这是一个更详细的方法来创建您正在寻找的结果和代码来测试操作。
#include <stdio.h>
void printBits(int n)
{
int i = 31;
char bits[32];
for ( ; i >= 0; --i, n /= 2 )
{
bits[i]= n % 2;
}
for ( i = 0; i < 32; ++i )
{
printf("%d", bits[i]);
if ( (i+1)%8 == 0 )
{
putchar(' ');
}
}
}
int foo(int n1, int n2)
{
// copy 8th and 9th bit of n1 to 2nd and 3rd bit of n2
// (all indices are 0 based).
// Extract the 8th and 9th bits of n1
int k1 = 0x00000300;
int r1 = n1 & k1;
// Clear the 2nd and 3rd bits of n2.
int k2 = 0xFFFFFFF9;
int r2 = n2 & k2;
// Move the 8th and 9th bits of n1 by 6 to the right
// to put them in 2nd and 3rd places.
// Construct the result and return.
return (r1 >> 6) | r2;
}
int main(int argc, char** argv)
{
int n1 = atoi(argv[1]);
int n2 = atoi(argv[2]);
printf("Input n1: ");
printBits(n1);
printf("\n");
printf("Input n2: ");
printBits(n2);
printf("\n");
int n3 = foo(n1, n2);
printf("Result : ");
printBits(n3);
printf("\n");
}
示例输出:
./test-19 251282 85 Input n1: 00000000 00000011 11010101 10010010 Input n2: 00000000 00000000 00000000 10000000 Result : 00000000 00000000 00000000 10000100