[英]C Programming convert String representation of Hex to Hex
I am fairly new to C. I would like to convert a String representation of a HEX number to a actual Hex number ? 我对C相当陌生。我想将十六进制数字的String表示形式转换为实际的十六进制数字吗?
#include <stdio.h>
int main()
{
char buf[8] = "410C0000";
printf("%s\n",buf);
return 0;
}
I would like to break up the string and convert it into 4 inividual Hex numbers. 我想将字符串分解成4个独立的十六进制数字。 Which i can process further for calculations : 我可以进一步处理以进行计算:
0x41 0x0C 0x00 0x00
You can use sscanf
, which is a variant of scanf
that reads from a string rather than from a stdin or a file. 您可以使用sscanf
,它是scanf
的变体,它从字符串而不是从stdin或文件中读取。 Format specifier %X
specifies to treat the input as a hexadecimal number, %02X
additionally says to read exactly two digits, and %02hhX
additionally defines to store the result into a single byte (ie an unsigned char
, instead of a probably 64 bit integral value). 格式说明符%X
指定将输入视为十六进制数, %02X
另外表示要精确读取两位数, %02hhX
另外定义将结果存储到单个字节(即, unsigned char
,而不是可能的64位整数)值)。
The code could look as follows: 该代码如下所示:
int main()
{
char buf[8] = "410C0000";
unsigned char h0=0, h1=0, h2=0, h3=0;
sscanf(buf+6, "%02hhX", &h0);
sscanf(buf+4, "%02hhX", &h1);
sscanf(buf+2, "%02hhX", &h2);
sscanf(buf+0, "%02hhX", &h3);
printf("0x%02X 0x%02X 0x%02X 0x%02X\n",h3, h2, h1, h0);
return 0;
}
Output: 输出:
0x41 0x0C 0x00 0x00
BTW: buf
- as being of size 8 - will not contain a string terminating '\\0'
, so you will not be able to use it in printf
. 顺便说一句: buf
的大小为8-将不包含以'\\0'
结尾的字符串,因此您将无法在printf
使用它。 Write char buf[9]
if you want to use buf
as a string as well, eg when writing printf("%s\\n",buf)
. 如果还想将buf
用作字符串,请编写char buf[9]
,例如,在编写printf("%s\\n",buf)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.