Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active October 5, 2015 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovasoa/2778127 to your computer and use it in GitHub Desktop.
Save lovasoa/2778127 to your computer and use it in GitHub Desktop.
Simple bit manipulation
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv) {
unsigned char byte;
unsigned char i;
FILE *fi = stdin;
FILE *fo = stdout;
if (fi==NULL || fo==NULL) return 1;
while ( fread(&byte, 1, 1, fi) ) {
for (i=0; i<8; i++) {
fputc( (byte>>7)==1?'1':'0', fo );
byte <<= 1;
}
fputc(' ', fo );
}
fputc('\n', fo);
fclose(fo);
fclose(fi);
return 0;
}

C bit manipulation

Contenu

bin.c

Displays the contents of stdin as bits (a sequence of 0 and 1) on stdout

unbin.c

Does the contrary of bin.c. Decodes a sequence of 0 and 1 to actual binary data.

gray.c

Encodes stdin using grey code.

ungray.c

Decodes gray code.

Licence

Copyright (C) 2012 Ophir LOJKINE

All you want to do... Do it!
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv) {
unsigned char b;
FILE *fi = stdin;
FILE *fo = stdout;
if (fi==NULL || fo==NULL) return 1;
while (fread(&b, 1, 1, fi)) {
b = (b)^(b>>1);
fwrite(&b, 1, 1, fo);
}
fclose(fi);fclose(fo);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv) {
unsigned char b=0;
unsigned char byte=0;
unsigned char offset=0;
FILE *fi = stdin;
FILE *fo = stdout;
if (fi==NULL || fo==NULL) return 1;
while (fread(&b, 1, 1, fi)) {
if (b=='1' || b=='0') {
offset ++;
byte <<= 1;
if (b=='1') byte |= 1;
if (offset == 8) {
offset = 0;
fwrite(&byte, 1, 1, fo);
}
}
}
fclose(fi);fclose(fo);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv) {
unsigned char b;
FILE *fi = stdin;
FILE *fo = stdout;
if (fi==NULL || fo==NULL) return 1;
while (fread(&b, 1, 1, fi)) {
b ^= (b>>1) ^ (b>>2) ^ (b>>3) ^ (b>>4) ^ (b>>5) ^ (b>>6) ^ (b>>7);
fwrite(&b, 1, 1, fo);
}
fclose(fi);fclose(fo);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment