summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorlshprung <lshprung@yahoo.com>2022-05-24 13:36:00 -0700
committerlshprung <lshprung@yahoo.com>2022-05-24 13:36:00 -0700
commit1020469ff5b17ba057078363aeca48177f1260f1 (patch)
tree65a41d9dcf6efb39be4f0812585b5da91fa210ac
parent69c1e5264137c5ff3369acf3c0ece8fbbce67dec (diff)
Added support for 2s compliment negatives
-rw-r--r--int2bin.c17
1 files 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;