Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- void showBits(unsigned a){
- for(int i = sizeof(a) * 8 - 1; i >= 0; i--) {
- printf("%d",(a >> i) & 1);
- if (i % 4 == 0) {
- putchar(' ');
- }
- }
- puts("");
- }
- int getBitsParity(uint32_t x) {
- int parity = 0;
- if (x) {
- do {
- parity ^= 1;
- } while(x &= x - 1);
- }
- return parity;
- }
- //each nibble is replaced with its parity
- uint32_t parity2(uint32_t x) {
- uint32_t r = 0;
- for (int nibId = 0; nibId < 8; nibId++) {
- uint32_t nibble = (x >> (nibId * 4)) & 0xF;
- if (getBitsParity(nibble)) {
- r |= (1 << (nibId * 4));
- }
- }
- return r;
- }
- int main(void) {
- uint32_t x;
- printf("x="); scanf("%u", &x);
- showBits(x);
- printf("%08x\n", parity2(x));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement