Created
February 21, 2015 18:03
-
-
Save yusuke024/8107750a715fa7ec7190 to your computer and use it in GitHub Desktop.
Bit manipulation in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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'; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run with:
gcc -c *.c; gcc *.o; ./a.out