[英]Wrong value returned when converting from raw character to hex equivalent
I have an application where the input is a raw set of bytes and I want to see the two-digit hex code of each of those bytes. 我有一个应用程序,其中输入是一组原始字节,我想查看每个字节的两位十六进制代码。 For now I'm trying to get the proper hex code for one byte.
现在,我正在尝试获取一个字节的正确十六进制代码。 This is my code:
这是我的代码:
#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;
}
I expected to see ff appear on the screen, but instead I see 00. How do I fix this? 我希望看到ff出现在屏幕上,但我看到的是00。如何解决此问题?
And if I change 0xFF
after aval[2]=
to 0x31
or '1'
(since 1 is the actual value for ascii code 0x31) then I want to see 31
appear on the screen. 而且,如果我在
aval[2]=
之后将0xFF
更改为0x31
或'1'
(因为1是ASCII代码0x31的实际值),那么我希望看到31
出现在屏幕上。
aval[2]={0xFF,0x00}; aval [2] = {0xFF,0x00};
This is not ascii. 这不是ASCII。
aval[]={'f', 'f',0x00}; aval [] = {'f','f',0x00};
Or 要么
aval[]="ff"; aval [] =“ ff”;
And try again 然后再试一次
The values can be printed directly without strtol
这些值可以直接打印而无需
strtol
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
unsigned char aval[9]={0xFF,0x00,0xF0,0x0f,0xAA,0xBB,0x00,0x0E,0xFF};
char hexv[20]; //value for output
char *hexvc = hexv;
memset(hexv,0,19); //clear output
for ( int each = 0; sizeof aval > each; ++each){
sprintf ( hexvc,"%02hhx",aval[each]);
hexvc += 2;
}
printf("%s\n",hexv);
return 0;
}
char aval[] = {0x66, 0x66, 0x00};
0x66
是ascii中的0x66
'f'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.