将uint8_t转换为十六进制字符串(2位数字)

时间:2019-08-30 08:41:12

标签: c

我目前正在使用以下内容将uint8_t打印到hex

for(int j = 0; j < len; j++) {
    printf("%02X ", bytes[j]);
}

是否可以在没有for循环的情况下执行此操作,而只是将结果分配给变量?

2 个答案:

答案 0 :(得分:4)

这是一种简单的方法:

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

bool to_hex(char* dest, size_t dest_len, const uint8_t* values, size_t val_len) {
    if(dest_len < (val_len*2+1)) /* check that dest is large enough */
        return false;
    *dest = '\0'; /* in case val_len==0 */
    while(val_len--) {
        /* sprintf directly to where dest points */
        sprintf(dest, "%02X", *values);
        dest += 2;
        ++values;
    }
    return true;
}

int main() {
    uint8_t values[256];
    char buf[sizeof(values)*2+1]; /* one extra for \0 */

    for(size_t i=0; i<256; ++i)
        values[i] = i;

    if(to_hex(buf, sizeof(buf), values, sizeof(values)))
        printf("%s\n", buf);
}

输出:

000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF

为完整起见,这是一个使用查找表而非sprintf的自包含版本:

bool to_hex(char* dest, size_t dest_len, const uint8_t* values, size_t val_len) {
    static const char hex_table[] = "0123456789ABCDEF";
    if(dest_len < (val_len*2+1)) /* check that dest is large enough */
        return false;
    while(val_len--) {
        /* shift down the top nibble and pick a char from the hex_table */
        *dest++ = hex_table[*values >> 4];
        /* extract the bottom nibble and pick a char from the hex_table */
        *dest++ = hex_table[*values++ & 0xF];
    }
    *dest = 0;
    return true;
}

答案 1 :(得分:2)

我个人会选择sprintf approach,但是如果您非常不想使用其中一种库api,则可以使用以下方法:

char HexLookUp[] = "0123456789abcdef";    
void bytes2hex (unsigned char *src, char *out, int len)
{
    while(len--)
    {
        *out++ = HexLookUp[*src >> 4];
        *out++ = HexLookUp[*src & 0x0F];
        src++;
    }
    *out = 0;
}

测试代码:

int main(void) 
{
    unsigned char bytes[] = {0x00, 0x01, 0x02, 0x03, 0xDE, 0xAD, 0xBE, 0xEF, 0xCC};
    char buffer[sizeof(bytes)*2 + 1];
    bytes2hex(bytes, buffer, sizeof(bytes));
    printf("%s\n",buffer);
    return 0;
}

输出:

  

00010203deadbeefcc