Including decimal equivalent of a char in a character array

大憨熊 提交于 2019-12-10 17:57:26

问题


How do I create a character array using decimal/hexadecimal representation of characters instead of actual characters.

Reason I ask is because I am writing C code and I need to create a string that includes characters that are not used in English language. That string would then be parsed and displayed to an LCD Screen.

For example '\0' decodes to 0, and '\n' to 10. Are there any more of these special characters that i can sacrifice to display custom characters. I could send "Temperature is 10\d C" and degree sign is printed instead of '\d'. Something like this would be great.


回答1:


Assuming you have a character code that is a degree sign on your display (with a custom display, I wouldn't necessarily expect it to "live" at the common place in the extended IBM ASCII character set, or that the display supports Unicode character encoding) then you can use the encoding \nnn or \xhh, where nnn is up to three digits in octal (base 8) or hh is up to two digits of hex code. Unfortunately, there is no decimal encoding available - Dennis Ritchie and/or Brian Kernighan were probably more used to using octal, as that was quite common at the time when C was first developed.

E.g.

 char *str = "ABC\101\102\103";
 cout << str << endl;

should print ABCABC (assuming ASCII encoding)




回答2:


You can directly write

char myValues[] = {1,10,33,...};



回答3:


Use \u00b0 to make a degree sign (I simply looked up the unicode code for it)

This requires unicode support in the terminal.




回答4:


Simple, use std::ostringstream and casting of the characters:

std::string s = "hello world";

std::ostringstream os;
for (auto const& c : s)
    os << static_cast<unsigned>(c) << ' ';

std::cout << "\"" << s << "\" in ASCII is \"" << os.str() << "\"\n";

Prints:

"hello world" in ASCII is "104 101 108 108 111 32 119 111 114 108 100 "



回答5:


A little more research and i found answer to my own question.

Characters follower by a '\' are called escape sequence.

You can put octal equivalent of ascii in your string by using escape sequence from'\000' to '\777'.

Same goes for hex, 'x00' to 'xFF'.

I am printing my custom characters by using 'xC1' to 'xC8', as i only had 8 custom characters.

Every thing is done in a single line of code: lcd_putc("Degree \xC1")



来源:https://stackoverflow.com/questions/18184147/including-decimal-equivalent-of-a-char-in-a-character-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!