From 1020469ff5b17ba057078363aeca48177f1260f1 Mon Sep 17 00:00:00 2001 From: lshprung Date: Tue, 24 May 2022 13:36:00 -0700 Subject: Added support for 2s compliment negatives --- int2bin.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/int2bin.c b/int2bin.c index 4917a3d..0f965d7 100644 --- a/int2bin.c +++ b/int2bin.c @@ -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; -- cgit