Skip to content

Instantly share code, notes, and snippets.

@yusuke024
Created July 4, 2015 10:25
Show Gist options
  • Save yusuke024/b020fd789cc48f39924c to your computer and use it in GitHub Desktop.
Save yusuke024/b020fd789cc48f39924c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
void printBits(char *bits, size_t n) {
for (int i = 0; i < n; ++i) {
printf("%c", (bits[i/8] & (1 << (7 - i%8))) == 0 ? '0' : '1');
}
printf("\n");
}
void invertBits(char *bits, size_t n) {
int i = 0, j = n-1;
char ib, jb;
while (i < j) {
ib = (bits[i/8] & (1 << (7 - i%8))) > 0 ? 1 : 0;
jb = (bits[j/8] & (1 << (7 - j%8))) > 0 ? 1 : 0;
bits[i/8] = (bits[i/8] & ~(1 << (7 - i%8))) | (jb << (7 - i%8));
bits[j/8] = (bits[j/8] & ~(1 << (7 - j%8))) | (ib << (7 - j%8));
++i;
--j;
}
}
int main(int argc, char *argv[]) {
size_t n = strlen(argv[1]);
char c[2] = { 0x8f, 0x4f };
printBits(c, 13);
invertBits(c, 13);
printBits(c, 13);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment