Selasa, 26 Maret 2013

Ubah String Binary ke hexa

Hari ini mau tulis snipet code kecil yakni untuk mengubah string biner ke hexa.
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 ;
}

void main() {
        unsigned char buff[1024];
        unsigned char output[24];
        int len, i;
        unsigned long long int lld;

        memset(output, 0x0, sizeof(output));
        memset(buff, 0x0, sizeof(buff));
        strcpy(buff, "10000000");

        len = strbin2hex(buff, output);

        for(i = 0; i < len; i++) printf("%02X ", output[i]);
        printf("\n");
}

Kalau dicompile dan dirun maka kan muncul 
80 00

Sekian dari saya, selamat mencoba :)

0 komentar:

Posting Komentar