繁体   English   中英

从原始字符转换为等效十六进制时返回错误的值

[英]Wrong value returned when converting from raw character to hex equivalent

我有一个应用程序,其中输入是一组原始字节,我想查看每个字节的两位十六进制代码。 现在,我正在尝试获取一个字节的正确十六进制代码。 这是我的代码:

#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出现在屏幕上。

aval [2] = {0xFF,0x00};

这不是ASCII。

aval [] = {'f','f',0x00};

要么

aval [] =“ ff”;

然后再试一次

这些值可以直接打印而无需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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM