Created
August 8, 2017 03:56
-
-
Save ryankshah/bf45790b968540cdabdeef702883ddbb to your computer and use it in GitHub Desktop.
Convert String to Bits in C
This file contains 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
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