我有一个查询。我有一串ascii值。我正在从Hex文件中读取。认为字符串是“0004EB9C”。这是在unsigned char缓冲区中复制的。
unsigned char buff[8] = {'0','0','0','4','E','B','9','C'}
unsigned int j = 0;
现在必须通过UART通信传输此字符串或信息。认为这代表我执行的RAM地址。我需要将这个8字节的ascii值存储在unsigned int中。我找不到一种方法,请关注这一点。 复制/转换此字符串后的输出应该像
printf("%x",j);
这应该打印
Output : 0x0004EB9C
提前感谢!!
答案 0 :(得分:1)
set answer to 0
for each character
left-shift answer by 4
if the character is between '0' and '9' inclusive
subtract '0' from it
else
subtract 'A' from it and add 10
bitwise-or this into answer
答案 1 :(得分:0)
#include <stdio.h>
int main(){
char data[] = "004EB59C";
const int len = sizeof(data)/sizeof(char)-1;
int i,value[sizeof(data)/sizeof(char)-1];
unsigned int j = 0;
for(i=0;i<len;++i)
sscanf(data+i, "%1x",value + i);
for(i=0;i<len;i++)
{
j <<= 4;
j |= (0x0f & value[i]);
printf("%x\n",j);
}
return 0;
}
更正代码。如果可能的话,我会要求即兴发表这个答案。
答案 2 :(得分:0)
存储为unsigned j
unsigned char buff[8] = {'0','0','0','4','E','B','9','C'}
unsigned char buff2[sizeof buff + 1];
memcpy(buff2, buff, sizeof buff);
buff2[sizeof buff] = '\0';
unsigned int j = (unsigned) strtoul(buff2, 0, 16);
通过j
打印
printf("%#08x",j);
直接通过buff
fputs("0x", stdout);
for (size_t i = 0; i < sizeof buff; i++)
fputc(tolower(buff[i]), stdout);