I am using the division approach to converting an unsigned int whole number to binary. I have the following code. However, I do not get any output from the program after compiling and executing (I just get new line escape).
#include <stdio.h>
/*
unsigned int is 0 or greater than 0
convert unsigned int into binary.
*/
const int ARRAY_SIZE = 100;
void reverseCharArray(char *x, int len) {
for (int end = len - 1, beg = 0; beg < end; end--, beg++) {
char temp = x[beg];
x[beg] = x[end];
x[end] = temp;
}
}
void convertWholeNumberToBinary(unsigned int x, char *result) {
int i = 0;
while (x != 0) {
result[i] = x % 2;
x = x / 2;
i++;
}
reverseCharArray(result, ARRAY_SIZE);
}
int main() {
char result[ARRAY_SIZE];
convertWholeNumberToBinary(294, result);
// 100100110
printf("%s\n", result);
return 0;
}
The desired output is "100100110" when the input is 294. I expected stdout to show "100100110". I know I am missing something but I can't wrap my head around it at the moment.
You're making a few mistakes, but the big one is when you reverse your char array. You're passing ARRAY_SIZE
but the array hasn't been fully filled because we can't enter a 99-bit integer, so there are still indeterminate values at the end of the array which get swapped to the front of it. If the last character at the end of the array just happens to be a '\0'
you now have a null-terminated empty string to print.
Instead, you want to pass i
, which indicates the actual length of the string at the end of the loop.
You're also adding either 1
or 0
to the string, rather than the char equivalent.
Thirdly, you're not initializing your char array in main
so its contents are indeterminate. Now, since your other functions don't explicitly null terminate the string, you run into undefined behavior territory when printing it as a string. Simple solution: initialize that char array with ""
, which may not work if this is compiled with a C (vs. C++) compiler.
Alternatively simply insert the null terminator in convertWholeNumberToBinary
.
#include <stdio.h>
const int ARRAY_SIZE = 100;
void reverseCharArray(char *x, int len) {
for (int end = len - 1, beg = 0; beg < end; end--, beg++) {
char temp = x[beg];
x[beg] = x[end];
x[end] = temp;
}
}
void convertWholeNumberToBinary(unsigned int x, char *result) {
int i = 0;
while (x != 0) {
result[i++] = '0' + (x % 2);
x /= 2;
}
result[i] = '\0';
reverseCharArray(result, i);
}
int main() {
char result[ARRAY_SIZE];
convertWholeNumberToBinary(294, result);
printf("%s\n", result);
return 0;
}