c-字符数组中的位操作



我正在编写一个函数来设置/取消设置无符号字符数组中的位。我收到了以下指示。

在此任务中,位0是最高有效位。还假定该无符号字符正好是8位(1字节(。因此,例如8是第二个无符号字符字节中最左边的位,而位17是第三个无符号字符字节中的第二高位。因此,检查数字170(0xAA十六进制格式,二进制10101010(,最多有效位,即位0的值为1。

基于此,我写了以下内容。

/* NOTE:
* -----------
* The parameter binary data (const unsigned char*) in all the functions 
* below is likely to hold more than 8 bits. You should take this into 
* account when implementing your functions.
*/
/* DESCRIPTION:
* ------------
* The function sets a bit with index i as active (1) in the parameter
* binary data.
*
* PARAMETERS:
* ------------
* unsigned char* data: an array of binary data.
* int i: the index of the bit which to set as active (1).
*
* RETURNS:
* ------------
* Nothing.
*
*/
void op_bit_set(unsigned char *data, int i)
{
data[i/32] |= 1 << (i%32); 
}
/* DESCRIPTION:
* ------------
* The function sets a bit with index i as inactive (0) in the parameter
* binary data.
*
* PARAMETERS:
* ------------
* unsigned char* data: an array of binary data.
* int i: the index of the bit which to set as active (1).
*
* RETURNS:
* ------------
* Nothing.
*
*/
void op_bit_unset(unsigned char *data, int i)
{
data[i/32] &= ~(1 << (i%32)); 
}

当我用给定的数据进行测试时,我的答案是错误的。

unsigned char arr[2] = {0, 0};
op_bit_set(arr, 0);
*** Testing your op_bit_set function.. 
At first arr[0] == 0x00 and arr[1] == 0x00 
Setting bit 0 arr[0] is 0x01, should be 0x80 
arr[1] is 0x00, should be 0x00

我的答案基于我在这里读到的内容:http://www.mathcs.emory.edu/~张/课程/255/教学大纲/1-C-introl/bit-array.html

正如Thomas所提到的,您使用的是一个有8位的无符号字符。因此,确定索引和位数的逻辑应该使用8而不是32。

此外,由于最高有效位是最左边的位,您必须将0x80(或128(右移i,这将为您想要设置/取消设置的特定位提供掩码。

最后,代码应该是这样的。

void op_bit_set(unsigned char *data, int i)
{
data[i/8] |= 0x80 >> (i%8); 
}
void op_bit_unset(unsigned char *data, int i)
{
data[i/8] &= ~(0x80 >> (i%8)); 
}

最新更新