diff options
author | lshprung <lshprung@yahoo.com> | 2022-05-24 13:36:00 -0700 |
---|---|---|
committer | lshprung <lshprung@yahoo.com> | 2022-05-24 13:36:00 -0700 |
commit | 1020469ff5b17ba057078363aeca48177f1260f1 (patch) | |
tree | 65a41d9dcf6efb39be4f0812585b5da91fa210ac /int2bin.c | |
parent | 69c1e5264137c5ff3369acf3c0ece8fbbce67dec (diff) |
Added support for 2s compliment negatives
Diffstat (limited to 'int2bin.c')
-rw-r--r-- | int2bin.c | 17 |
1 files changed, 15 insertions, 2 deletions
@@ -19,20 +19,33 @@ void print_help(char *name){ char *to_bin(int n, int bits){ char *out = malloc(sizeof(char) * (bits+1)); + bool negative = false; //keep track of whether n is negative (and requires 2s compliment notation) int i; out[bits] = '\0'; + //handle negative numbers + if(n < 0){ + n = -1 * (n + 1); + negative = true; + } + for(i = bits-1; i >= 0; --i){ out[i] = (n & 1 ? '1' : '0'); - n /= 2; + n = n >> 1; + } + + //if negative, flip the bits + if(negative){ + for(i = 0; i < bits; ++i){ + out[i] = 48 + ((out[i] - 47) % 2); + } } return out; } - int main(int argc, char **argv){ int i; |