c - wrong initialization of a short bit by bit - why set incorrectly the most significant bits of the last two variables? -
i wrote program exercise myself bitwise operations. in follow lines of code try assign value 3 short bit-by-bit. print them through bit_print() function.
#include <stdio.h> #include <limits.h> void bit_print(short a) { int i; int n = sizeof(short) * char_bit; /* in limits.h */ short mask = 1 << (n - 1); /* mask = 100...0 */ (i = 1; <= n; ++i) { putchar(((a & mask) == 0) ? '0' : '1'); <<= 1; if (i % char_bit == 0 && < n) putchar(' '); } } int main(void){ short alice = 0, betty = 0, carol = 0; int x; char c; printf("put 16 bits alice: "); (x = 15; x >= 0; --x){ if ((c = getchar()) == '1') alice |= 1 << x; else alice |= 0 << x; } putchar('\n'); printf("put 16 bits betty: "); (x = 15; x >= 0; --x){ if ((c = getchar()) == '1') betty |= 1 << x; else betty |= 0 << x; } putchar('\n'); printf("put 16 bits carol: "); (x = 15; x >= 0; --x){ if ((c = getchar()) == '1') carol |= 1 << x; else carol |= 0 << x; } putchar('\n'); bit_print(alice); putchar('\n'); bit_print(betty); putchar('\n'); bit_print(carol); putchar('\n'); return 0; } for reason, if input 1111111111111111 3 times, executing program follow output:
put 16 bits alice: 1111111111111111 put 16 bits betty: 1111111111111111 put 16 bits carol: 1111111111111111 11111111 11111111 01111111 11111111 10111111 11111111 as can see, significant bits of last 2 variables, betty , carol, have zeroes in places should not. why?
when using getchar(), newline character press end end of input gets picked up, you're not accounting it.
you'll need read , discard newlines @ end of each loop account this:
#include <stdio.h> #include <limits.h> void bit_print(short a) { int i; int n = sizeof(short) * char_bit; /* in limits.h */ short mask = 1 << (n - 1); /* mask = 100...0 */ (i = 1; <= n; ++i) { putchar(((a & mask) == 0) ? '0' : '1'); <<= 1; if (i % char_bit == 0 && < n) putchar(' '); } } int main(void){ short alice = 0, betty = 0, carol = 0; int x; char c; printf("put 16 bits alice: "); (x = 15; x >= 0; --x){ if ((c = getchar()) == '1') alice |= 1 << x; else alice |= 0 << x; } putchar('\n'); getchar(); printf("put 16 bits betty: "); (x = 15; x >= 0; --x){ if ((c = getchar()) == '1') betty |= 1 << x; else betty |= 0 << x; } putchar('\n'); getchar(); printf("put 16 bits carol: "); (x = 15; x >= 0; --x){ if ((c = getchar()) == '1') carol |= 1 << x; else carol |= 0 << x; } putchar('\n'); getchar(); bit_print(alice); putchar('\n'); bit_print(betty); putchar('\n'); bit_print(carol); putchar('\n'); return 0; }
Comments
Post a Comment