Contohnya "1000" => 0x08
Langsung liat ke kode di bawah ini :
unsigned char gethexa(unsigned char *strhex) {
int i;
unsigned char arrbin[16][5]= {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
unsigned char byte[16] = {0x0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
for(i = 0; i < 16; i++)
if(strcmp(strhex, arrbin[i]) == 0) return byte[i];
return 0x0;
}
/************************************************
* Change string biner to hexa.
* e.x : "1000" => 0x08
* Params :
* - binstr = string biner
* - binhex = hexa biner
*
*/
int strbin2hex(unsigned char *binstr, unsigned char *binhex) {
int i, j = 0, len;
unsigned char bintmp[5];
unsigned char hextmp;
memset(bintmp, 0x0, sizeof(bintmp));
for(i = 0; i < strlen(binstr); i+=8) {
memcpy(bintmp, &binstr[i], 4);
hextmp = gethexa(bintmp);
hextmp <<= 4;
memcpy(bintmp, &binstr[i+4], 4);
hextmp |= gethexa(bintmp);
binhex[j] = hextmp;
printf("binhex[%d] %x\n", j, binhex[j]);
len = ++j;
}
return len ;
}