How to check is bit value equals to 1?

跟風遠走 提交于 2019-12-11 12:18:52

问题


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:


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;
}

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.



来源:https://stackoverflow.com/questions/32297880/how-to-check-is-bit-value-equals-to-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!