#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 SHOULD NOT use "xor" operator, is there a way to do that without really long code?
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if(argc == 2){
int iParity = 0;
char c;
int iSel = 0;
for (int i = 0; i < strlen(argv[1]); i++){
c = argv[1][i] - '0';
iSel = (iParity<<1) + c;
switch(iSel){
case 1:
case 2:
iParity = 1;
break;
case 0:
case 3:
iParity = 0;
break;
default:
break;
}
}
printf("Parity is: %d\n", iParity);
}
return 0;
}
Basically this is the solution my teacher told us in the out lesson, and yes, you had to convert a string index into a integer, and create a bit mask that works similar to a XOR operator, and that's pretty much it.
Addendum (by a commenter, scs):
The way the expression iSel = (iParity<<1) + c
and the following switch
statement work is that they implement the truth table for the XOR operator, like this:
iParity |
c |
shift expression | XOR output |
---|---|---|---|
0 | 0 | 0 | 0 |
0 | 1 | 1 | 1 |
1 | 0 | 2 | 1 |
1 | 1 | 3 | 0 |
In the end, the effect is the same as the much simpler
iParity = iParity ^ c;