Hex to char array in C

后端 未结 11 1115
广开言路
广开言路 2020-11-30 09:04

Given a string of hex values i.e. e.g. \"0011223344\" so that\'s 0x00, 0x11 etc.

How do I add these values to a char array?

Equivalent to say:

<
11条回答
  •  自闭症患者
    2020-11-30 09:59

    Below are my hex2bin and bin2hex implementations.

    These functions:

    • Are public domain (feel free to copy and paste)
    • Are simple
    • Are correct (i.e., tested)
    • Perform error handling (-1 means invalid hex string)

    hex2bin

    static char h2b(char c) {
        return '0'<=c && c<='9' ? c - '0'      :
               'A'<=c && c<='F' ? c - 'A' + 10 :
               'a'<=c && c<='f' ? c - 'a' + 10 :
               /* else */         -1;
    }
    
    int hex2bin(unsigned char* bin,  unsigned int bin_len, const char* hex) {
        for(unsigned int i=0; i

    bin2hex

    static char b2h(unsigned char b, int upper) {
        return b<10 ? '0'+b : (upper?'A':'a')+b-10;
    }
    
    void bin2hex(char* hex, const unsigned char* bin, unsigned int bin_len, int upper) {
        for(unsigned int i=0; i>4,   upper);
            hex[2*i+1] = b2h(bin[i]&0x0F, upper);
        }
    }
    

提交回复
热议问题