简体   繁体   中英

C/C++ integer to hex to char array to char

Well I have been trying to convert this integer into hex and have successfully done so but I need to use this hex for setting something. Now for this I need to use a char not a char array. Nothing else has worked without manually setting it. Maybe the problem lies in the issue that I use sprintf for the conversion to hex but either way I am sure there is a way to complete this task. Now What I need to change is have the output be char z but I haven't found a way to get this to work. Any help is greatly appreciated. Thanks

EDIT: now thi code may not make sense directly because it is incomplete and I saw no purpose inputting unrelated code. int x will never be over 100 and the whole point is to convert this into a hex and write it to the memory of a setting I have. So I have been trying to figure out how to convert the integer into hex into a char. nonstring as someone pointed out even though sprintf converts it to a string stored in a char as I just noticed. But I need to take the int convert to hex and assign that to a char variable forbuse later on. And that is where I am stuck. I do not know the best way to go about completely all that in a format and way without going into a string and other things.

VOID WriteSetting(int x)
{
    char output[8];
    sprintf(output, "0x%X", x);
    char z = 0x46
    unsigned char y = z
}

Working Code:

VOID WriteSetting(int x)
{
    unsigned char y = (unsigned char)x;
    Settingdb.Subset.Set = y;
}

你有没有尝试过

printf("0x%X", z);

While the C++ standards do not explicitly require it, the size of a character is sometimes a byte, and an integer 4 bytes. I presume that this is why you are using an array of 4 characters.

So when you have an integer type and try to cram it into a single character, you'll lose precision.

PS A more precise explanation of sizes of data types is here: What does the C++ standard state the size of int, long type to be?

If what you want is for:

WriteSetting(70);

or

WriteSetting(0x46);

to do the same thing as

char z = 0x46;
unsigned char y = z;

then all you need to do is:

void WriteSetting(int x)
{
    unsigned char y = x;
}

Integers don't have any inherent base - they're just numbers. There's no difference at all between unsigned char y = 0x46; and unsigned char y = 70; .

void WriteSetting(unsigned char *y, int x){
    if(x > 100){
        fprintf(stderr, "x value(%d) is invalid at %s\n", x, __func__);
        return ;
    }
    *y = x;//There is no need for conversion probably
}

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