Advertisement
STANAANDREY

rev nibbles and nibbles bits

Nov 1st, 2022 (edited)
1,013
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 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 revNibbles(unsigned a) {
  14.   const int nbNr = sizeof(a) * 2;
  15.   const unsigned mask = (1 << 4) - 1;
  16.   unsigned r = 0;
  17.   for (int nbId = 0; nbId < nbNr; nbId++) {
  18.     unsigned nb = (a >> (nbId * 4)) & mask;
  19.     r |= (nb << ((nbNr - 1) * 4 - nbId * 4));
  20.   }
  21.   return r;
  22. }
  23.  
  24. unsigned revNibBits(unsigned nb) {
  25.   unsigned r = 0;
  26.   for (int i = 0; i < 4; i++) {
  27.     if ((nb & (1 << i))) {
  28.       r |= 1 << (3 - i);
  29.     } else{
  30.       r &= ~(1 << (3 - i));
  31.     }
  32.   }
  33.   return r;
  34. }
  35.  
  36. unsigned revAllNibBits(unsigned a) {
  37.   const int nbNr = sizeof(a) * 2;
  38.   const unsigned mask = (1 << 4) - 1;
  39.   unsigned r = 0;
  40.   for (int nbId = 0; nbId < nbNr; nbId++) {
  41.     unsigned nb = (a >> (nbId * 4)) & mask;
  42.     r |= (revNibBits(nb) << (nbId * 4));
  43.   }
  44.   return r;
  45. }
  46.  
  47. int main(void) {
  48.   unsigned a;
  49.   scanf("%u", &a);
  50.  
  51.   printBits(a);
  52.   printBits(revNibbles(a));
  53.   printBits(revAllNibBits(a));
  54.  
  55.   return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement