【发布时间】:2019-10-15 07:52:08
【问题描述】:
我有一个应用程序,其中输入是一组原始字节,我想查看每个字节的两位十六进制代码。现在我正在尝试为一个字节获取正确的十六进制代码。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char hexvc; //= ascii code for hex value
char aval[2]={0xFF,0x00}; //Our raw 1 byte data. can't print actual code here
char hexv[20]; //value for output
memset(hexv,0,19); //clear output
hexvc=strtol(aval,NULL,16) & 0xFF;
if (hexvc != '\0'){
sprintf(hexv,"%02hx",hexvc);
}else{
//hexvc always equals 0. why not FFh?
strcpy(hexv,"00");
}
printf("%s\n",hexv);
return 0;
}
我希望看到 ff 出现在屏幕上,但我看到的是 00。 我该如何解决?
如果我在 aval[2]= 之后将 0xFF 更改为 0x31 或 '1'(因为 1 是 ascii 代码 0x31 的实际值),那么我希望看到 31 出现在屏幕上。
【问题讨论】:
-
strtol将字符串转换为长整数。您传入的字符串中的第一个字符是 0xFF,后跟一个空终止符。你似乎需要一个与strtol相反的函数。
标签: c binary hex ascii data-conversion