Skip to content

Instantly share code, notes, and snippets.

@ryankshah
Created August 8, 2017 03:56
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 ryankshah/bf45790b968540cdabdeef702883ddbb to your computer and use it in GitHub Desktop.
Save ryankshah/bf45790b968540cdabdeef702883ddbb to your computer and use it in GitHub Desktop.
Convert String to Bits in C
char * convertStringToBits(char * string) {
int i;
int stringLength = strlen(string);
int mask = 0x80; /* 10000000 */
char *charArray;
charArray = malloc(8 * stringLength + 1);
if(charArray == NULL) {
printf("An error occured!\n");
return NULL; //error - cant use charArray
}
for(i = 0; i < stringLength; i++) {
mask = 0x80;
char c = string[i];
int x = 0;
while(mask > 0) {
char n = (c & mask) > 0;
printf("%d", n);
charArray[x++] = n;
mask >>= 1; /* move the bit down */
}
printf("\n");
}
return charArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment