For the sake of simplicity, let’s just assume the integer I am passing to this function is 9 which is 1001 in binary.
It has been my goal for a while now to write my own integer to binary function in C. The way I used to figure out binary values for number in shorthand was as followed (using 9 as mentioned above):
9 / 2 = 4.5 (remainder) = 1
4 / 2 = 2 (no remainder) = 0
2 / 2 = 1 (no remainder) = 0
1 / 1 = 1 (remainder) = 1
So if you reverse the 1 0 0 1 we get you will have the binary value of 9 which is still 1 0 0 1.
But then after looking over this site I found that the binary value of an integer can be found with some “simple” bitwise arithmetic. I found a function on another post on this site and adapted it into a function of my own:
char *itob(int integer)
{
char *bin = 0X00, *tmp;
int bff = 0;
while(integer)
{
if(!(tmp = realloc(bin, bff + 1)))
{
free(bin);
printf("\nError! Memory allocation failed while building binary string.");
return 0x00;
}
bin = tmp;
if(integer & 1) bin[bff++] = '1';
else bin[bff++] = '0';
integer >>= 1;
}
bin[bff+1] = 0x00;
return bin;
}
Here is how I understand what is going on as well as my questions (that appear as comments)
1001 & 1 = 1 so put a 1 into the buffer //what is & doing that makes it equate to 1? Is it because the first digit in that sequence is a 1?
shift the bits in 1001 to the right one time
0010 & 1 != 1 so move a 0 into the buffer //same question as before is & just looking at the 0 because it is the first digit in the sequence?
shift the bits in 0010 to the right one time
0100 & 1 != 1 so move a 0 into the buffer //same question as before
shift the bits in 0100 to the right one time
1000 & 1 = 1 so put a 1 into the buffer //same question as before (at this point I'm thinking my theory is correct but I'm still not entirely sure)
shift the bits in 1000 to the right one time
loop ends
So as mentioned in my comments this is what I believe is going on in my program but I’m not 100% sure. Also I’m not sure if this is the best way to be even converting decimal to binary. (I’m already aware that if integer were for whatever reason to be a 0 I would eventually be trying to dereference a NULL pointer when trying to free the memory allocated by itob() along with a few other hiccups) But besides the questions that I already asked earlier is there a better method or more appropriate way to do this conversion?
No, the sequence of tests and shifts is
The resulting integer 0 makes the loop terminate. So what this does is test each bit starting with the least significant bit and append a 0 or 1 in the buffer. That I’d say is backwards because when printed as a string the bit sequence is reversed from the one used most often, where the least significant bit is the rightmost one.