c语言hex与string互转

hex转string

void hex2str(uint8_t *input, uint16_t input_len, char *output)
{
    char *hexEncode = "0123456789ABCDEF";
    int i = 0, j = 0;

    for (i = 0; i < input_len; i++) {
        output[j++] = hexEncode[(input[i] >> 4) & 0xf];
        output[j++] = hexEncode[(input[i]) & 0xf];
    }
}

string转hex

#define isDigit(c)             (((c) <= '9' && (c) >= '0') ? (1) : (0))

static uint8_t hex2dec(char hex)
{
    if (isDigit(hex)) {
        return (hex - '0');
    }
    if (hex >= 'a' && hex <= 'f') {
        return (hex - 'a' + 10);
    }
    if (hex >= 'A' && hex <= 'F') {
        return (hex - 'A' + 10);
    }

    return 0;
}

static int str2hex(char *input, int input_len, unsigned char *output, int max_len)
{
    int             i = 0;
    uint8_t         ch0, ch1;

    if (input_len % 2 != 0) {
        return -1;
    }

    while (i < input_len / 2 && i < max_len) {
        ch0 = hex2dec((char)input[2 * i]);
        ch1 = hex2dec((char)input[2 * i + 1]);
        output[i] = (ch0 << 4 | ch1);
        i++;
    }
    return i;
}

你可能感兴趣的:(c语言)