How to display the binary values of negative numbers in C

1 Answer

0 votes
#include <stdio.h>

char *toBinFormat(int n);

int main(int argc, char **argv) 
{ 
    for (int i = -1; i > -16; i--)
         printf("%s\n", toBinFormat(i));
         
    return 0;
}
char *toBinFormat(int n)
{
    static char binary_value[9]; // without static binary_value is a local 
                                 // array that disappear 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:

11111111
11111110
11111101
11111100
11111011
11111010
11111001
11111000
11110111
11110110
11110101
11110100
11110011
11110010
11110001

*/

 



answered Jun 27, 2015 by avibootz

Related questions

1 answer 281 views
1 answer 214 views
1 answer 121 views
1 answer 340 views
1 answer 146 views
...