如何转换十六进制在C ASCII使用和不使用的sprintf? [英] How to convert Hex to Ascii in C with and without using sprintf?
问题描述
我用与strtol
将字符串转换为十六进制,现在我需要把它打印到屏幕。我不知道我是否可以使用的sprintf
,因为我只有20K的内存对这款主板使用。替代的欢迎。
I used strtol
to convert a string to hex, now I need to print it to the screen. I'm not sure if I can use sprintf
since I only have 20k of memory to use on this board. Alternatives welcome.
推荐答案
要手动做到这一点,最简单的方法是有一个表映射到半字节ASCII:
To do this manually, the easiest way is to have a table mapping nybbles to ASCII:
static const char nybble_chars[] = "0123456789ABCDEF";
然后一个字节转换成2个十六进制字符 - 假设 unsigned char型
是一个字节最好再presentation,但没有作出关于其规模的假设 - - 提取每个半字节,并获得CHAR它:
Then to convert a byte into 2 hex chars -- assuming unsigned char
is the best representation for a byte, but making no assumptions about its size -- extract each nybble and get the char for it:
void get_byte_hex( unsigned char b, char *ch1, char *ch2 ) {
*ch1 = nybble_chars[ ( b >> 4 ) & 0x0F ];
*ch2 = nybble_chars[ b & 0x0F ];
}
这直截了当地扩展到更广泛的数据类型,而应在广泛的架构产生相当简洁code。
This extends straightforwardly to wider data types, and should generate reasonably concise code across a wide range of architectures.
这篇关于如何转换十六进制在C ASCII使用和不使用的sprintf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!