Search code examples
carduinomicrocontrolleravratmega

Take in a character and output its ASCII hex value


I'm programming (in C) my own serial functions for a UART on an ATMEGA microcontroller and I need to have the user input a single character and have it output its ASCII hex value,

i.e. if the user types an 'a', the output would be '0x61'. I wrote a function called

putvalue(unsigned char ch),

which takes in a single character and displays it to the screen, so now I just need to write a function which takes in the character and converts it to the characters which correspond to its ASCII hex value. So far I've done the following:

void puthexvalue(unsigned char ch) {
    putvalue(0x30) \\writes a '0' to the screen
    putvalue(0x78) \\writes an 'x' to the screen
    unsigned char ch1 = ch & 0xF0;
    unsigned char ch2 = (ch & 0x0F) >> 4;

So now I have the numerical values of the characters I want to print in ch1 and ch2, but I'm not sure how to actually find the ASCII value that corresponds to these numbers and print THAT value.

Any hints or help would be appreciated, thanks!

EDIT: It should be ch1 = ch & 0xf0 >> 4 and ch2 = ch & 0x0f.


Solution

  • Character codes from '0' to '9' are guaranteed to be continuous in C specification.

    Character codes from 'A' to 'Z' and from 'a' to 'z' are continuous in ASCII code.

    Therefore, if the number is between 0 and 9, you can get ASCII code by adding '0' to the number. If the number if between 10 and 15,you can get ASCII code by adding 'A' or 'a' to the number minus 10.

    Also your calculation of ch1 and ch2 are wrong: ch1 is multiplication of 16 (because lower bits are cleared) and ch2 will be always zero (because bits other than last 4 bits are cleard, then shifted right 4 bits).

    The implementation including fixed calculation of ch1 and ch2 will be like this:

    char getHexChar(unsigned char c) {
        if (c <= 9) return '0' + c;
        else if (c <= 15) return 'A' + (c - 10);
        else return '?';
    }
    
    void puthexvalue(unsigned char ch) {
        putvalue(0x30); //writes a '0' to the screen
        putvalue(0x78); //writes an 'x' to the screen
        unsigned char ch1 = (ch & 0xF0) >> 4;
        unsigned char ch2 = ch & 0x0F;
        putvalue(getHexChar(ch1));
        putvalue(getHexChar(ch2));
    }