/* * Program to show bit representation of long int, two ways -- * as a long int, and as a sequence of bytes */ #include #include void show(long n); void show_using_union(long n); void showbyte(unsigned char b); int main(void) { long n; puts("enter integer"); if (scanf("%ld", &n) != 1) { puts("invalid input") ; return 1; } printf("%ld considered as long:\n", n); show(n); printf("%ld considered as sequence of bytes:\n", n); show_using_union(n); return 0; } /* * show bit representation of n, treating it as a long */ void show(long n) { unsigned char byte_mask = ~((unsigned char) 0); for (int byte_index = 0; byte_index < sizeof(n); ++byte_index) { unsigned char b = (n >> (sizeof n - 1 - byte_index)*CHAR_BIT) & byte_mask; showbyte(b); putchar(' '); } putchar('\n'); } /* union to allow viewing "long" as sequence of bytes */ typedef union { long n; unsigned char bytes[sizeof(long)]; } long_bytes_t; /* * show bit representation of n, treating it as a sequence of bytes */ void show_using_union(long n) { long_bytes_t work; work.n = n; for (int i = 0; i < sizeof(n); ++i) { showbyte(work.bytes[i]); putchar(' '); } putchar('\n'); } /* show byte as bits */ void showbyte(unsigned char b) { for (unsigned char mask = 1 << (CHAR_BIT-1); mask > 0; mask >>= 1) { if ((mask & b) > 0) putchar('1') ; else putchar('0'); } }