C语言 C 是否有任何字符到十六进制函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2455245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any char to hexadecimal function for C?
提问by VGe0rge
I have a char array with data from a text file and I need to convert it to hexadecimal format. Is there such a function for C language.
我有一个包含文本文件数据的字符数组,我需要将其转换为十六进制格式。C语言有没有这样的功能。
Thank you in advance!
先感谢您!
回答by John Bode
If I understand the question correctly (no guarantees there), you have a text string representing a number in decimal format ("1234"), and you want to convert it to a string in hexadecimal format ("4d2").
如果我正确理解了问题(不保证),您有一个表示十进制格式(“1234”)的数字的文本字符串,并且您想将其转换为十六进制格式(“4d2”)的字符串。
Assuming that's correct, your best bet will be to convert the input string to an integer using either sscanf()or strtol(), then use sprintf()with the %xconversion specifier to write the hex version to another string:
假设是正确的,你最好的选择将是使用输入字符串为整数或者转换sscanf()或者strtol(),然后用sprintf()与%x转换说明写的十六进制版本到另一个字符串:
char text[] = "1234";
char result[SIZE]; // where SIZE is big enough to hold any converted value
int val;
val = (int) strtol(text, NULL, 0); // error checking omitted for brevity
sprintf(result, "%x", val);
回答by EvilTeach
I am assuming that you want to be able to display the hex values of individual byes in your array, sort of like the output of a dump command. This is a method of displaying one byte from that array.
我假设您希望能够显示数组中各个字节的十六进制值,有点像转储命令的输出。这是一种显示该数组中一个字节的方法。
The leading zero on the format is needed to guarantee consistent width on output. You can upper or lower case the X, to get upper or lower case representations. I recommend treating them as unsigned, so there is no confusion about sign bits.
需要格式上的前导零以保证输出的宽度一致。您可以大写或小写 X,以获得大写或小写表示。我建议将它们视为无符号,这样就不会混淆符号位。
unsigned char c = 0x41;
printf("%02X", c);
回答by mctylr
You can use atoiand sprintf/ snprintf. Here's a simple example.
您可以使用atoi和sprintf/ snprintf。这是一个简单的例子。
char* c = "23";
int number = atoi(c);
snprintf( buf, sizeof(buf), "%x", number );

