Hex to char array in C

后端 未结 11 1131
广开言路
广开言路 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:45

    Let's say this is a little-endian ascii platform. Maybe the OP meant "array of char" rather than "string".. We work with pairs of char and bit masking.. note shiftyness of x16..

    /* not my original work, on stacko somewhere ? */
    
    for (i=0;i < 4;i++) {
    
        char a = string[2 * i];
        char b = string[2 * i + 1];
    
        array[i] = (((encode(a) * 16) & 0xF0) + (encode(b) & 0x0F));
     }
    

    and function encode() is defined...

    unsigned char encode(char x) {     /* Function to encode a hex character */
    /****************************************************************************
     * these offsets should all be decimal ..x validated for hex..              *
     ****************************************************************************/
        if (x >= '0' && x <= '9')         /* 0-9 is offset by hex 30 */
            return (x - 0x30);
        else if (x >= 'a' && x <= 'f')    /* a-f offset by hex 57 */
            return(x - 0x57);
        else if (x >= 'A' && x <= 'F')    /* A-F offset by hex 37 */
            return(x - 0x37);
    }
    

    This approach floats around elsewhere, it is not my original work, but it is old. Not liked by the purists because it is non-portable, but extension would be trivial.

提交回复
热议问题