Advertisement
STANAANDREY

parity2

Oct 26th, 2022 (edited)
860
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. void showBits(unsigned a){
  5.   for(int i = sizeof(a) * 8 - 1; i >= 0; i--) {
  6.     printf("%d",(a >> i) & 1);
  7.     if (i % 4 == 0) {
  8.       putchar(' ');
  9.     }
  10.   }
  11.   puts("");
  12. }
  13.  
  14. int getBitsParity(uint32_t x) {
  15.   int parity = 0;
  16.   if (x) {
  17.     do {
  18.       parity ^= 1;
  19.     } while(x &= x - 1);
  20.   }
  21.   return parity;
  22. }
  23.  
  24.  
  25. //each nibble is replaced with its parity
  26. uint32_t parity2(uint32_t x) {
  27.   uint32_t r = 0;
  28.   for (int nibId = 0; nibId < 8; nibId++) {
  29.     uint32_t nibble = (x >> (nibId * 4)) & 0xF;
  30.     if (getBitsParity(nibble)) {
  31.       r |= (1 << (nibId * 4));
  32.     }
  33.   }
  34.   return r;
  35. }
  36.  
  37. int main(void) {
  38.   uint32_t x;
  39.   printf("x="); scanf("%u", &x);
  40.   showBits(x);
  41.   printf("%08x\n", parity2(x));
  42.   return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement