Skip to content

Instantly share code, notes, and snippets.

@markandrus
Last active August 29, 2015 14:04
Show Gist options
  • Save markandrus/72afd36526432e9be951 to your computer and use it in GitHub Desktop.
Save markandrus/72afd36526432e9be951 to your computer and use it in GitHub Desktop.
parity.c
#include <stdio.h>
#include <stdlib.h>
void print_bits(int i) {
printf("\n ");
int n = sizeof(int) * 8;
for (int j = n-1; j >= 0; j--) {
if (!((j+1) % 8)) {
printf(" ");
}
char p = (i & (1 << j)) >> j;
printf("%d", p);
}
printf("\n\n");
}
char parity(int i) {
char p = 0;
int n = sizeof(int) * 8;
for (int j = 0; j < n; j++) {
p += (i & (1 << j)) >> j;
}
return p % 2;
}
void usage(char *name) {
printf("Usage: %s INT\n", name);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
usage(argv[0]);
return 1;
}
int i = atoi(argv[1]);
print_bits(i);
printf("Parity of %d is %d.\n", i, parity(i));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment