# decimal representation of number to binary

Hallo,
are there any functions in cuda runtime, that perform conversion of int type number in decimal representation to any structure carrying binary representation of that number? Or simply, is there function which enables reading of integer’s bits?

Thanks,

Dalibor

I’m not aware of any built-in ones, but you can always write your own with bit shifts, or maybe with a union. The CUDA MAth API has some bit-level integer intrinsics, but not what you’re looking for as far as I can tell.

To just get the nth bit in an integer i, you can use (i & ( 1 > n

The cuda integer intrinsics list can be found at:
http://docs.nvidia.com/cuda/cuda-math-api/index.html#group__CUDA__MATH__INTRINSIC__INT

but I am still a little bit confused about your solution. The operator > is relation operator which returns true (0) or false (1). The operator & is bitwise AND operator - evaluates the AND operation for each bit pair of two input integers.

So lets say for example that i want to obtain the second bit of unsigned int i = 3 (counted from the first bit which is responsible for addition of 2^0=1 to decimal representation of number)

According to formula which you wrote above I get something like this:

1. Step: 1>2, the result of this operation is 0.
2. Step: 3 & 0 which is equal to …0011 AND …0000 (… means a lot of zeros), thats equal to …0000

which is incorrect result. at which point am I wrong?

Thanks, Dalibor.

Sorry about that, the forum apparently doesn’t like less than signs. Those were supposed to be bit-shifts.

If we say a shift left (i.e. double chevron less-than) is SHIFT_L, and a shift right is SHIFT_R
then it’d be

(i & (1 SHIFT_L n)) SHIFT_R n

so the SHIFT_L by n will create your mask by shifting the 1 to the nth bit, then when you take the bit-wise and of it and i, you get the ith bit. The SHIFT_R by n will shift that bit back to its original position.

For example:

``````void print_binary(int num)
{
printf("%d in binary:\n");
for (int i = 0; i < 32; i++)
{
int bit_val = (num & (1 SHIFT_L i)) SHIFT_R i;
printf(" %d ", bit_val);

}
printf("\n");
}
``````

Sorry for the cryptic syntax, but hopefully you get the idea

Also just as a heads up it looks like the backslashes for newlines were stripped in the above code sample

Sorry about the issues with the (lack of) faithful reproduction of code posted to the forums. The two issues of backslashes simply disappearing and ‘less than’ characters causing the rest of the line, or even the rest of the code, to disappear are known, and I have reported them more than once. I don’t know when this will be fixed.

If forum users observe addtional formatting issues in their posts, please let me know and I will forward these reports to the appropriate people. It would be helpful if you could provide a link to the forum thread that demonstrates the defect.

Perfect, thanks a lot for help.