Advertisement
STANAANDREY

pack unpack bits

Nov 1st, 2022
1,017
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.68 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void printBits(unsigned x) {
  4.   for (int i = sizeof(x) * 8 - 1; i >= 0; i--) {
  5.     printf("%d", 1 & (x >> i));
  6.     if (i % 4 == 0) {
  7.       putchar(' ');
  8.     }
  9.   }
  10.   puts("");
  11. }
  12.  
  13. unsigned char pack(unsigned a, unsigned b) {
  14.   unsigned char r = 0;
  15.   r |= a;
  16.   r |= (b << 4);
  17.   return r;
  18. }
  19.  
  20. void unpack(unsigned char ch) {
  21.   unsigned mask = (1 << 4) - 1;
  22.   unsigned fi = mask & ch;
  23.   unsigned se = mask & (ch >> 4);
  24.   printf("%u\n%u\n", fi, se);
  25. }
  26.  
  27. int main(void) {
  28.   unsigned a, b;
  29.   scanf("%u", &a);
  30.   scanf("%u", &b);
  31.  
  32.   printBits(a);
  33.   printBits(b);
  34.  
  35.   unsigned char ch = pack(a, b);
  36.   printBits(ch);
  37.   unpack(ch);
  38.  
  39.   return 0;
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement