#include <stdio.h>
char *toBinFormat(int n);
int main(int argc, char **argv)
{
printf("The binary value of %d is %s\n", 7, toBinFormat(7));
printf("The binary value of %d is %s\n", 30, toBinFormat(30));
printf("The binary value of %d is %s\n", 32, toBinFormat(32));
printf("The binary value of %d is %s\n", 64, toBinFormat(64));
return(0);
}
char *toBinFormat(int n)
{
static char binary_value[9]; // without static binary_value is a local array
// that didn't exist after return
int i;
for(i = 0; i < 8; i++)
{
binary_value[i] = n & 0x80 ? '1' : '0';
n <<= 1;
}
binary_value[i] = '\0';
return binary_value;
}
/*
run:
The binary value of 7 is 00000111
The binary value of 30 is 00011110
The binary value of 32 is 00100000
The binary value of 64 is 01000000
*/