Home > Net >  Is there a way to do a parity check using bit shifting, and without using xor of a string with bits?
Is there a way to do a parity check using bit shifting, and without using xor of a string with bits?

Time:11-20

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]){
    if(argc == 2){
        int iParity = 0;
        int bitmask = 0;
        for(int i = 1; i < strlen(argv[1]); i  ){
            switch(argv[1][i]){
                case '0':
                    if(iParity == 0)
                        iParity = 0;
                    else
                        iParity = 1;
                    break;
                case '1':
                    if(iParity == 0)
                        iParity = 1;
                    else
                        iParity = 0;
                    break;
                default:
                    break;
            }
        }
        printf("The parity is: %d", iParity);
    }
}

Basically I put the input directly into the execute line, like "./check 10010" check is the name of the program, and afterwards I need to put binary number, and I need to parity check the number using bit shifting ( << or >> ) and I DON'T HAVE TO use "xor" operator, is there a way to do that without really long code?

CodePudding user response:

Here are 2 solutions without the use of exclusive or:

You can add the bit values directly from the string representation and use & to select the parity of the result:

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc == 2) {
        const char *s = argv[1];
        int iParity = 0 >> 0;  // required bitshift :)
        for (int i = 0; p[i] != '\0'; i  ) {
            iParity  = p[i] == '1';
        }
        iParity &= 1;
        printf("The parity is: %d\n", iParity);
    }
    return 0;
}

Your teacher might expect another approach, converting the number from text to an int and computing the parity from its bits:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc == 2) {
        // convert from base 2 text representation
        unsigned long number = strtoul(argv[1], NULL, 2);
        int iParity = 0;
        while (number != 0) {
            iParity  = number & 1;
            number = number >> 1;
        }
        iParity &= 1;
        printf("The parity is: %d\n", iParity);
    }
    return 0;
}

CodePudding user response:

Very naive - but no XOR's

int verynaive(uint32_t v)
{
    int result = 0;
    while(v)
    {
        result  = v & 1;
        v >>= 1;
    }
    return result & 1;
}

The fastest method I know is to use a lookup table.

int parity(uint32_t v)
{
    uint16_t lookup = 0b110100110010110;
    v ^= v >> 16;
    v ^= v >> 8;
    v ^= v >> 4;
    return (lookup >> (v & 0x0f)) & 1;
}

or a bit more naive

int func( uint32_t x ) 
{
    int32_t y;
    for ( y=0; x; y = !y )
    x ^= x & -x;
    return y;
}
  • Related