比如一个字符串是16进制的格式:
str="00744d4c";
怎么能转化成真正的16进制放入char数组中,像这样
char data[8]={0x00,0x74,0x4d,0x4c};
新手求教,等待大婶解答
------解决思路----------------------
INT a;
sscanf("00744d4c", "%x", &a);
------解决思路----------------------
strtoul, _strtoul_l, wcstoul, _wcstoul_l
------解决思路----------------------
API StrToIntEx
https://msdn.microsoft.com/en-us/library/bb773451.aspx
BOOL StrToIntEx(
_In_ PCTSTR pszString,
STIF_FLAGS dwFlags,
_Out_ int *piRet
);
Parameters
pszString [in]
Type: PCTSTR
A pointer to the null-terminated string to be converted. For further details concerning the valid forms of the string, see the Remarks section.
dwFlags
Type: STIF_FLAGS
One of the following values that specify how pszString should be parsed for its conversion to an integer.
STIF_DEFAULT
The string at pszString contains the representation of a decimal value.
STIF_SUPPORT_HEX
The string at pszString contains the representation of either a decimal or hexadecimal value. Note that in hexadecimal representations, the characters A-F are case-insensitive.
piRet [out]
Type: int*
A pointer to an int that receives the converted string. For instance, in the case of the string "123", the integer pointed to by this value receives the integer value 123.
If this function returns FALSE, this value is undefined.
If the value returned is too large to be contained in a variable of type int, this parameter contains the 32 low-order bits of the value. Any high-order bits beyond that are lost.
------解决思路----------------------
char最大表示值是0x7f
你应该用unsigned char,最大值可以达到0xff
------解决思路----------------------
“char最大表示值是0x7f” 0-》127
0x80 -》0xFF = -128 -》 -1
------解决思路----------------------
作为一个C程序员,对
scanf,sscanf,fscanf
printf,sprintf,fprintf
这类函数的用法,还是要做到“拳不离手,曲不离口”的。
//比如一个字符串是16进制的格式:
//str="00744d4c";
//怎么能转化成真正的16进制放入char数组中,像这样
//char data[8]={0x00,0x74,0x4d,0x4c};
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <memory.h>
char str[]="00744d4c";
char *data;
int L,v,i;
int main() {
L=strlen(str)/2;
data=(char *)malloc(L);
if (NULL==data) return 1;
for (i=0;i<L;i++) {
sscanf(str+i*2,"%2x",&v);
data[i]=v;
printf("data[%d]:0x%02x\n",i,(unsigned char)data[i]);
}
free(data);
return 0;
}
//data[0]:0x00
//data[1]:0x74
//data[2]:0x4d
//data[3]:0x4c
//