I'm a newbie in C language, so forgive me the beginners question.
#include<stdio.h>
#include<stdlib.h>
char *decimal_to_binary(int);
void main() {
int buffer;
while (1) {
printf("Type your number here: \n\r");
scanf_s("%d", &buffer);
printf("After conversion to binary system your number is: \n\r");
printf("%s", decimal_to_binary(buffer));
printf("\n");
}
}
int get_byte_value(int num, int n) {
// int x = (num >> (8*n)) & 0xff
return 0;
}
char* decimal_to_binary(int num) {
int tab[sizeof(int) * 8] = { 0 };
char binary[sizeof(int) * 8] = { 0 };
int i = 0;
while (num) {
tab[i] = num % 2;
num /= 2;
i++;
}
for (int j = i - 1, k = 0; j >= 0; j--, k++) {
binary[k] = tab[j];
}
return binary;
}
When I print out whatever came back from decimal_to_binary I get some garbage (a smiley face character) instead of the binary representation. But when I do printf
inside the last loop of the decimal_to_binary
function, I'm getting correct values. So what did I do wrong?