我正在阅读Programming in C, 4th edn作者:史蒂芬·科尚。
练习:编写一个名为 bit_test()
的函数,它接受两个参数:一个 unsigned int
和一个位数 n
。如果位号 n
在字内打开,则函数返回 1,如果关闭,则返回 0。假设位号 0 引用整数内最左边的位。还要编写一个名为 bit_set()
的相应函数,它接受两个参数:一个 unsigned int
和一个位数 n
。让函数返回将整数内部的位 n
打开的结果。
这是其 forum 上的练习答案之一.
12-5
-----
/* test bit n in word to see if it is on
assumes words are 32 bits long */
int bit_test (unsigned int word, int n)
{
if ( n < 0 || n > 31 )
return 0;
if ( (word >> (31 - n)) & 0x1 )
return 1;
else
return 0;
}
unsigned int bit_set (unsigned int word, int n)
{
if ( n < 0 || n > 31 )
return 0;
return word | (1 << (31 - n));
}
现在我尝试这样理解它,根据我的理解,它总是返回 0。这个函数实际上是做什么的?
最佳答案
它只是检查是否设置了一个位。
它假设 unsigned int 在该特定系统上以 32 位存储。
为什么要检查?
需要检查以确保安全(我不会移动负值或大于 31 的值),因为第一个提示是错误,而第二个则无用,因为它返回 0。
它在 (word >> (31 - n)) & 0x1 )
中的真正作用?
x x y x x x x x x
0 1 2 3 4 5 6 7 8
|-----------|
8-2=6
(这里我考虑了 9 位字而不是 32 位字。在您的情况下,它将是 31-3=28
所以右移6位
0 0 0 0 0 0 x x y
现在如何检查它是否已设置?
0 0 0 0 0 0 x x y
& 0 0 0 0 0 0 0 0 1
________________________
0 0 0 0 0 0 0 0 y if it is set it returns 1 else 0
if that bit is et the result will be 1 else 0.
bit_set 的作用是什么?
它返回第 n 位集。
So if you input
0001 0010 1
and set bit is 0 (you want to set bit at position 0) then you will get
1001 0010 1
返回词| (1 << (31 - n));
让这个词是0001 1001 1 您想要设置位 2 [0 索引]
0001 1001 1
| 0010 0000 0
<小时/>0011 1001 1
您必须对该值应用逻辑或运算。
如何获取该值?
Here we just want this number
0010 0000 0
|-------|
6 shift needed (left shift)
1 << (8-2) ---> is how you get it.
或者在你的情况下1<<(31-n)
现在我明白你的想法是错误的......
You considered 25
0000 0000 0000 0000 0000 0000 0000 1101
The bit in 3rd (0 indexing) position is this
000[0] 0000 0000 0000 0000 0000 0000 1101
该位未设置或为 0。
尝试数字 25 的第 29 个位置,您将得到 1 作为答案。
关于c - bit_test() 函数的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413293/