Home > Back-end >  How do I convert char 20 to 0x20?
How do I convert char 20 to 0x20?

Time:12-16

I have a character returned from something which returns character 20. I am trying to send this number 20 to another thing for it to display on an LCD, however when I put in 20, it shows 14. so I have tried multiple things like:

char x = 20;
char y = '0x'   x;

to literally try and combine them into "0x20" (20 in hexadecimal). I know when typing in "0x20" into my function it returns with the number 20, however trying the code I just showed you always returns "14" or some weird other form that is not number.

So what I am asking is: If I have the char 20 that is supposed to show the number "20" since it gets sent somewhere in hex/binary, how do I make it "0x20"?

Small note: number 20 is 0x14 in hex when converted. I am trying to show 20 instead (well send 0x20). I have to use numbers that are higher than this so I have to make sure that i am always doing 0x20, 0x21.. 0x30... etc.

any char that is "1", "2" (under 10) is fine. it is just numbers 10 and above.

CodePudding user response:

unsigned convert(unsigned char x)
{
    return (x % 10)   ((x / 10) % 10) * 16   ((x / 100) % 10) * 16 * 16;
}

int main(void)
{
    printf("Converted: 0x%x\n", convert(20));
    printf("Converted: 0x%x\n", convert(120));
    printf("Converted: 0x%x\n", convert(155));
    printf("Converted: 0x%x\n", convert(255));
}

CodePudding user response:

Get the tens digit of the value and multiply that by 16 to get the first digit of the corresponding hex value. Then add the ones digit of the number and add that.

char dec = 20;
char hex = 16 * (dec / 10)   dec % 10;

This assumes it's only up to 2 digits. The other answer shows how to do it for up to 3 digits.

  • Related