简体   繁体   English

如何在C中将char ASCII转换为十六进制等值?

[英]How to convert char ASCII to hex equivilent in C?

So basically, I am writing code to control an LCD via a micro-controller. 因此,基本上,我正在编写代码以通过微控制器控制LCD。 (atmega 32) I have the following in my main method: (atmega 32)我的主要方法有以下几点:

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

and here is my sendString method: 这是我的sendString方法:

// 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. 然后sendString方法需要转换每个字符。 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. 我是C语言的新手,正在慢慢学习。 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. 我有种感觉,我正在解决所有这些错误,因为我在某处读到一个char实际上实际上存储为8位int。 How can I get my method to return the HEX value for each input char? 如何获取返回每个输入字符的十六进制值的方法?

In C, a char is an 8 bit signed integer, you can just use hexadecimal to represent it. 在C语言中,char是一个8位有符号整数,您可以仅使用十六进制表示它。 In the following lines, a,b and c have the same value, an 8 bit integer. 在以下各行中,a,b和c具有相同的值,即8位整数。

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. 一个问题是您不能使用sizeof()来获取字符串的长度。 In C, strings ends with NULL, so you can iterate it until you find it. 在C中,字符串以NULL结尾,因此您可以迭代它直到找到它。 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]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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