# How to check is bit value equals to 1?

1

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" ... ?

}
``````

c#
opencl
bit
asked on Stack Overflow Aug 30, 2015 by Kechup • edited May 23, 2017 by Community

4

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.