简体   繁体   中英

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?

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,0x00};

This is not ascii.

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

Or

aval[]="ff";

And try again

The values can be printed directly without 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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