Search code examples
ccharhexasciilcd

How to convert char ASCII to hex equivilent in C?


So basically, I am writing code to control an LCD via a micro-controller. (atmega 32) I have the following in my main method:

unsigned char str1[9] = "It Works!";
sendString(str1);

and here is my sendString method:

// Converts each char to hex and sends to LCD
void sendString(unsigned char *string){ 


    sendCommand(0x01); // Clear screen 0x01 = 00000001
    _delay_ms(2);
    sendCommand(0x38); // Put in 8-bit mode
    _delay_us(50);
    sendCommand(0b0001110); // LCD on and set cursor off
    _delay_us(50);

    //For each char in string, write to the LCD
    for(int i = 0; i < sizeof(string); i++){
        convertASCIIToHex(string[i]);
    }
}

Then the sendString method needs to convert each char. Here is what I have so far:

unsigned int convertASCIIToHex(unsigned char *ch)
{
    int hexEquivilent[sizeof(ch)] = {0};

    for(int i = 0; i < sizeof(ch); i++){
        // TODO - HOW DO I CONVERT FROM CHAR TO HEX????
    }

    return hexEquivilent;
 }

So how would i go about doing the conversion? I am completely new to C and am learning slowly. I have a feeling I am going about this all wrong as I read somewhere that a char is actually stored as an 8 bit int anyway. How can I get my method to return the HEX value for each input char?


Solution

  • In C, a char is an 8 bit signed integer, you can just use hexadecimal to represent it. In the following lines, a,b and c have the same value, an 8 bit integer.

    char a = 0x30;  //Hexadecimal representation
    char b = 48;    //Decimal representation
    char c = '0';   //ASCII representation
    

    I think that what you need its just sending the characters of the string, without any conversion to hexadecimal. One problem is that you can't use sizeof() to get the length of a string. In C, strings ends with NULL, so you can iterate it until you find it. Try this:

    // Converts each char to hex and sends to LCD
    void sendString(unsigned char *string){ 
    
    
        sendCommand(0x01); // Clear screen 0x01 = 00000001
        _delay_ms(2);
        sendCommand(0x38); // Put in 8-bit mode
        _delay_us(50);
        sendCommand(0b0001110); // LCD on and set cursor off
        _delay_us(50);
    
        //For each char in string, write to the LCD
        for(int i = 0; string[i]; i++){
            sendCommand(string[i]);
        }
    }