My homework is to make a simple function that, given a unsigned char,
should returns its bit string representation.
I tried to drop down some code (as follows) but it doesn't work.
Compiling is successfully, but print8bit() doesn't return anything.
Was wondering where I'm mistaking. Thanks in advance for your help.
/* code starts here */
char* print8bit (unsigned char n)
{
char s[9]; /* Allocate an array of 8+1 char */
int i, j; /* Counter variables */
for (j=7,i=0; j>=0,i<=7 ; j--,i++)
{
if(n & (1<<i))
s[j]='1';
else
s[j]='0';
}
s[8]='\0'; /* Marker of end of string */
return s; /* Return the first address of char array? */
}
int main(void)
{
char* str = print8bit(128); /* str[] now should be '1000000' */
printf("%d: %s", 128, str); /* on stdout is printed only '128:' */
return 0;
}
/* code ends here */
should returns its bit string representation.
I tried to drop down some code (as follows) but it doesn't work.
Compiling is successfully, but print8bit() doesn't return anything.
Was wondering where I'm mistaking. Thanks in advance for your help.
/* code starts here */
char* print8bit (unsigned char n)
{
char s[9]; /* Allocate an array of 8+1 char */
int i, j; /* Counter variables */
for (j=7,i=0; j>=0,i<=7 ; j--,i++)
{
if(n & (1<<i))
s[j]='1';
else
s[j]='0';
}
s[8]='\0'; /* Marker of end of string */
return s; /* Return the first address of char array? */
}
int main(void)
{
char* str = print8bit(128); /* str[] now should be '1000000' */
printf("%d: %s", 128, str); /* on stdout is printed only '128:' */
return 0;
}
/* code ends here */
Comment