- You change the bits.
- You cannot use leftover x as an indicator to complete the loop.
Consider, for example, 4.
After the first iteration of the loop:
rem == 0
converted == 0
x == 2
After the second iteration of the loop:
rem == 0
converted == 0
x == 1
And then you set the conversion to 1.
Try:
int i = sizeof(x) * 8; // i is now number of bits in x
while (i>0) {
--i;
converted *= 10;
converted |= (x >> i) & 1;
// Shift x right to get bit number i in the rightmost position,
// then and with 1 to remove any bits left of bit number i,
// and finally or it into the rightmost position in converted
}
x unsigned char (8 ) 129 ( 10000001)
i = 8, unsigned char * 8. i 7. x (129) 7 , 1. OR'ed converted, 1. converted 10 ( 10), x 6 ( 2) AND 1 ( 0). 0 converted, 10. , converted 10, x OR'ed converted. converted 1000000.
converted 10 10000000, x right 0 bits, 129. x 1, 1. 1 OR'ed converted, 10000001.