From 9114a8bda9c70dbf643daf9c55d2f3c37fcf4c68 Mon Sep 17 00:00:00 2001 From: Rushil Umaretiya Date: Tue, 20 Feb 2024 03:05:38 -0500 Subject: [PATCH] finished signed and twos --- signed.c | 29 +++++++++++++++++++++++++++-- twos.c | 44 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 69 insertions(+), 4 deletions(-) diff --git a/signed.c b/signed.c index 6603bbf..d440b6b 100644 --- a/signed.c +++ b/signed.c @@ -1,8 +1,33 @@ -// PID: 9DigitPidNoSpacesOrDashes +// PID: 730677144 // I pledge the COMP 211 honor code. #include +#include -int main() { +int main(int argc, char *argv[]) { + int num = atoi(argv[1]); + + if (num < -32768 || num > 32767) { + printf("not possible\n"); + return 0; + } + + if (argv[1][0] == "-") { + printf("1"); + num = -num; + } else { + printf("0"); + } + + for (int i = 15; i > 0; i--) { + if (num >= (1 << i)) { + printf("1"); + num -= (1 << i); + } else { + printf("0"); + } + } + + printf("\n"); return EXIT_SUCCESS; } diff --git a/twos.c b/twos.c index 6603bbf..e6dcffa 100644 --- a/twos.c +++ b/twos.c @@ -1,8 +1,48 @@ -// PID: 9DigitPidNoSpacesOrDashes +// PID: 730677144 // I pledge the COMP 211 honor code. #include +#include + +int main(int argc, char *argv[]) { + int num = abs(atoi(argv[1])); + char out[16]; + + if (num > 65535) { + printf("not possible\n"); + return 0; + } + + for (int i = 15; i >= 0; i--) { + if (num >= (1 << i)) { + out[15-i] = '1'; + num -= (1 << i); + } else { + out[15-i] = '0'; + } + + } + + if (argv[1][0] == '-') { + for (int i = 0; i < 16; i++) { + if (out[i] == '0') { + out[i] = '1'; + } else { + out[i] = '0'; + } + } + + for (int i = 15; i >= 0; i--) { + if (out[i] == '1') { + out[i] = '0'; + } else { + out[i] = '1'; + break; + } + } + } + + printf("%s\n", out); -int main() { return EXIT_SUCCESS; }