- You're reversing the bits.
- You cannot use the remains of x as an indicator when to terminate the loop.
Consider e.g. 4.
After first loop iteration:
rem == 0
converted == 0
x == 2
After second loop iteration:
rem == 0
converted == 0
x == 1
And then you set converted 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
}
Running the above code with x as an unsigned char (8 bits) with value 129 (binary 10000001)
Starting with i = 8
, size of unsigned char * 8. In the first loop iteration i
will be 7. We then take x
(129) and shift it right 7 bits, that gives the value 1. This is OR'ed into converted
which becomes 1. Next iteration, we start by multiplying converted
with 10 (so now it's 10), we then shift x
6 bits right (value becomes 2) and ANDs it with 1 (value becomes 0). We OR 0 with converted
, which is then still 10. 3rd-7th iteration do the same thing, converted
is multiplied with 10 and one specific bit is extracted from x
and OR'ed into converted
. After these iterations, converted
is 1000000.
In the last iteration, first converted
is multiplied with 10 and becomes 10000000, we shift x
right 0 bits, yielding the original value 129. We AND x with 1, this gives the value 1. 1 is then OR'ed into converted
, which becomes 10000001.