Skip to content

Instantly share code, notes, and snippets.

@yusuke024
Created February 21, 2015 18:03
Show Gist options
  • Save yusuke024/8107750a715fa7ec7190 to your computer and use it in GitHub Desktop.
Save yusuke024/8107750a715fa7ec7190 to your computer and use it in GitHub Desktop.
Bit manipulation in C
#include "bits.h"
const int NUM_BITS_IN_BYTE = 8;
int getbit(char c, int i) {
if (i >= NUM_BITS_IN_BYTE || i < 0) {
return -1;
}
return (c & (1 << i)) > 0;
}
void setbit(char *c,int i) {
if (i >= NUM_BITS_IN_BYTE || i < 0) {
return;
}
*c = ((char)(1 << i)) | *c;
}
void unsetbit(char *c, int i) {
if (i >= NUM_BITS_IN_BYTE || i < 0) {
return;
}
*c = ~((char)(1 << i)) & *c;
}
void getbitstr(char c, char *s) {
for (int i = 0; i < NUM_BITS_IN_BYTE; ++i) {
s[NUM_BITS_IN_BYTE-1-i] = getbit(c, i) > 0 ? '1' : '0';
}
}
#ifndef BITS_H
#define BITS_H
int getbit(char c, int i);
void setbit(char *c,int i);
void unsetbit(char *c, int i);
void getbitstr(char c, char *s);
#endif
#include <stdio.h>
#include "bits.h"
int main(int argc, char const *argv[]) {
char a = 1 << 4; // 0001 0000
a = a - 1; // 0000 1111
setbit(&a, 5); // 0010 1111
setbit(&a, 7); // 1010 1111
unsetbit(&a, 2); // 1010 1011
char s[9] = {0};
for (int i = sizeof(a)-1; i >= 0; --i) {
char *c = ((char *)&a);
getbitstr(*(c + i), s);
printf("%s", s);
}
printf("\n");
return 0;
}
@yusuke024
Copy link
Author

Run with:
gcc -c *.c; gcc *.o; ./a.out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment