#include <stdio.h>
char *toBinFormat(int n);
int main(int argc, char **argv)
{
int n = 32768;
printf("Dec | Hex | Bin\n");
for (int i = 0; i < 16; i++)
{
printf("%5d | 0x%04X | %s\n", n, n, toBinFormat(n));
n = n >> 1;
}
return(0);
}
char *toBinFormat(int n)
{
static char binary_value[17]; // without static binary_value is a local
// array that disappear after return
int i;
for(i = 0; i < 16; i++)
{
binary_value[i] = n & 0x8000 ? '1' : '0';
n <<= 1;
}
binary_value[i] = '\0';
return binary_value;
}
/*
run:
Dec | Hex | Bin
32768 | 0x8000 | 1000000000000000
16384 | 0x4000 | 0100000000000000
8192 | 0x2000 | 0010000000000000
4096 | 0x1000 | 0001000000000000
2048 | 0x0800 | 0000100000000000
1024 | 0x0400 | 0000010000000000
512 | 0x0200 | 0000001000000000
256 | 0x0100 | 0000000100000000
128 | 0x0080 | 0000000010000000
64 | 0x0040 | 0000000001000000
32 | 0x0020 | 0000000000100000
16 | 0x0010 | 0000000000010000
8 | 0x0008 | 0000000000001000
4 | 0x0004 | 0000000000000100
2 | 0x0002 | 0000000000000010
1 | 0x0001 | 0000000000000001
*/