From 7103f28467a9e89488b71eee13ed6b57e70ad03d Mon Sep 17 00:00:00 2001 From: Donna M Agogliati Date: Tue, 26 Mar 2019 14:18:45 -0400 Subject: [PATCH] Create swapdoublebytes.c --- swapdoublebytes.c | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 swapdoublebytes.c diff --git a/swapdoublebytes.c b/swapdoublebytes.c new file mode 100644 index 0000000..cb8f94e --- /dev/null +++ b/swapdoublebytes.c @@ -0,0 +1,48 @@ +#include + +/* + * Print the bits in n in four formats: + * + * hexadecimal + * decimal with bits interpreted as signed int. + * decimal with bits interpreted as unsigned int. + * binary + */ +void print_bits(int n) +{ + // print the integer in different format + printf("hex:%08X signed:%d unsigned:%u bits:", n, n, n); + + // a loop to print bits from most significant to least significant + // also an example of sizeof use + for (int i = sizeof(int) * 8 - 1; i >= 0; i --) + printf("%d", (n >> i) & 1); + printf("\n"); +} + +int main() +{ + int n; + + // Repeatedly read an integer 'n' from standard input and + // swap left and right double bytes into 'n1' if successful. + // To exit, press Ctrl-D or Ctr-C + while (scanf("%d", &n) == 1) { + + int n1 = 0; + int firsthalf = (n &0xFFFF0000) >> 16; + int secondhalf = (n &0x0000FFFF) << 16; + + n1 = (firsthalf|secondhalf); + + // Your code to swap left and right double bytes in n and + // save the changed value in n1. + // call function to print the bits in n and n1 + + print_bits(n); + print_bits(n1); + } + + /* Let the OS know everything is just peachy. */ + return 0; +}