Skip to content

Instantly share code, notes, and snippets.

@Ynn
Last active July 24, 2017 23:13
Show Gist options
  • Save Ynn/a963b1f0486e87f00de54fb6719ba879 to your computer and use it in GitHub Desktop.
Save Ynn/a963b1f0486e87f00de54fb6719ba879 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef unsigned char uint8_t;
void printBits(uint8_t num){
int size = sizeof(uint8_t);
unsigned int maxPow = 1<<(size*8-1);
int i=0,j;
for(;i<size;++i){
for(;i<size*8;++i){
// print last bit and shift left.
printf("%u",num&maxPow ? 1 : 0);
num = num<<1;
}
}
}
uint8_t * asBytes(char * s) {
int nelements=strlen(s)/2;
uint8_t * result = (uint8_t *) calloc(nelements,sizeof(uint8_t));
for(int i=0;i<nelements;i++){
result[i]=(uint8_t)strtol((char[]){s[i*2],s[i*2+1]}, NULL, 16);
}
return result;
}
main()
{
int i;
char * test = "0123456789abcdef";
uint8_t * result = asBytes(test);
for(i=0;i<strlen(test)/2;i++)
{
printBits(result[i]);
printf(" ");
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment