简体   繁体   中英

Fastest convesion from uint8 to hex char

Suppose I have an 1-byte wide integer (where only the lower 4 bits are actually active) and I want to convert it to its hex value as a char.

uint8_t original_int = 0xF; // will always be 0x0 to 0xF
char converted_int = // something that doesnt require a string to use the std library
                     // yet is still portable. i'd just like to use 1 char

Anything wrong with this?

uint8_t original_int = 0xF;
char converted_int = "0123456789ABCDEF"[original_int];

Using a string literal as your look up table is a bit funky. But however it's done a look up table is the way to go.

char converted_int = 
    original_int < 0xA ? 
    ('0' + original_int) : 
    ('A' + original_int - 0xA);

This one is memory-efficient. With pipeline execution, I think it is fast enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM