I want to return a 16BIT binary from a decimal number. I havt 2 Codes.
In the first one I tried to return a char array.
In the second one a have an output but it in the inverse order.
Maybe someone take a look at the codes.
Thanks
Output first Function: Þ0000000000010000es (x862uÿ¼×
#include <stdio.h>
#include <stdlib.h>
const int BIT = 16;
void binary(int);
char *bin(int);
int main() {
binary(16);
printf("\n");
printf("%s\n", bin(16));
return 0;
}
char *bin(int x) {
char * new = (char*)malloc(sizeof(char) * BIT + 1);
new[BIT] = '\0';
if (x >= 0 && x <= 65535) {
for (int i = 0; i < BIT; i++) {
if (x % 2 == 0) {
new[BIT - i] = '0';
} else {
new[BIT - i] = '1';
}
x = x / 2;
}
}
return new;
}
void binary(int x) {
if (x >= 0 && x <= 65535) {
for (int i = 0; i < BIT; i++) {
if (x % 2 == 0) {
printf("0");
} else {
printf("1");
}
x = x / 2;
}
}
}