Reputation:
void int_to_bin_digit(int in, int count, int* out)
{
int mask = 1U << (count-1); // LINE 1
int i;
for (i = 0; i < count; i++)
{
out[i] = (in & mask) ? 1 : 0; // LINE 3 (I don't understand it )
in <<= 1; // LINE 2
}
}
I needed a function that converts ints to binary.I didn't know how to make one myself as I never used bit operators. I found this one on here it does its job.
let's say we call the function like this int_to_bin_digit( 67,8,out)
I understand that line 1 gives mask the value 128 (1000 0000) and that line 2 makes 67 (0100 0011) go like this (not sure about this one )
i=0 (0100 0011)
-----------
i=1 (1000 0110)
i=2 (0000 1100)
i=3 (0001 1000)
i=4 (0011 0000)
i=5 (0110 0000)
i=6 (1100 0000)
i=7 (1000 0000) (loop stops here )
(0000 0000) (so we never get to this one I guess)
Does line 3 compare only the first 1 and return 1 if it's ==1 and return 0 if it's !=1? how does it work exactly?
EDIT : https://davidzych.com/converting-an-int-to-a-binary-string-in-c/ after reading this. I see that we only compare the first 1 inside in with the first 1 inside mask I don't understand why it won't just return 1 in everycase, since both numbers are != 0. What makes the program only compares the first bits?
Upvotes: 1
Views: 76
Reputation: 3592
Yes, your assumptions are almost all right.
LINE 1 is the mask of the count
-th least bit. LINE 3 tests if such bit is set in your in
number. The term &
stands for the "bitwise and", where "and" operates on bits and is only equal to 1 when both operands are equal to 1, and "bitwise" means it is applied to respective pairs of bits of the operands. LINE 2 then proceeds to shift all the bits of in
to the left, making n-th bit what was previously (n-1) bit.
But all in all, consider reading a tutorial about bitwise operations, this will make your life as a C programmer much easier.
Upvotes: 1