如何检查比特值等于1? [英] How to check is bit value equals to 1?
问题描述
我正在运行OpenCL内核.在某个时刻,我想检查变量中所选位置的位是否等于1?例如,我发现在C#中,我们可以使用代码
I have running OpenCL kernel. At some moment I want to check is bit at selected position in variable equals to one or not? For example, I found that in C# we can convert uint
to string containing bits using code like this:
// Here we will store our bit
string bit;
// Unsigned integer that will be converted
uint hex = 0xfffffffe;
// Perform conversion and store our string containing bits
string str = uint2bits(hex);
// Print all bits "11111111111111111111111111111110"
Console.WriteLine(str);
// Now get latest bit from string
bit = str.Substring(31, 1);
// And print it to console
Console.WriteLine(bit);
// This function converts uint to string containing bits
public static string uint2bits(uint x) {
char[] bits = new char[64];
int i = 0;
while (x != 0) {
bits[i++] = (x & 1) == 1 ? '1' : '0';
x >>= 1;
}
Array.Reverse(bits, 0, i);
return new string(bits);
}
如何像上面的代码那样在内核内部制作?
How to make inside kernel like in code above?
__kernel void hello(global read_only uint* param) {
/*
Do something with "param"
...
*/
int bit;
int index = 31;
/*
Store bit value ("0" or "1") at variable "bit"
...
*/
if (bit == 1) {
// ...
} else {
// ...
}
// Or maybe something more easy to check a bit value at "index" in "param" ... ?
}
在哪里可以了解更多信息?
Where I can read more about that?
推荐答案
通过用1<<b
进行掩码并将结果与零进行比较,可以检查数字中的b
位是设置为1还是0. /p>
You can check if a bit b
in a number is set to 1 or 0 by masking with 1<<b
, and comparing the result to zero:
static bool isBitSet(uint n, uint b) {
return (n & (1U << b)) != 0;
}
二进制文件中的1 << b
的值由第b
个位置中的单个1
从背面开始,从零开始计数,在所有其他位置为零.当使用按位AND运算符&
将此掩码应用于n
时,将得到一个数字n
的单个位,而在所有其他位置为零.因此,当n
的第b
位设置为零时,总体操作的结果为零,否则为非零.
The value of 1 << b
in binary is composed of a single 1
in b
-th position counting from the back starting at zero, and zeros in all other positions. When you apply this mask to n
with the bitwise AND operator &
you get a single bit of number n
, and zeros in all other positions. Therefore, the result of the overall operation is zero when b
-th bit of n
is set to zero, and a non-zero otherwise.
这篇关于如何检查比特值等于1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!