3

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.

Hassan
  • 870
  • 13
  • 25

5 Answers5

6

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)

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

You can directly write

char myValues[] = {1,10,33,...};
KasF
  • 212
  • 1
  • 6
1

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

This requires unicode support in the terminal.

tohava
  • 5,344
  • 1
  • 25
  • 47
  • I don't think this actually requires Unicode (wide character) support; it's sufficient if the narrow character set used supports the degree character. The compiler can then convert `'\u00b0'` to an appropriate `char` value, which might or might not be `0xb0`. – MSalters Aug 12 '13 at 10:57
0

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 "
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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")

Hassan
  • 870
  • 13
  • 25
  • I posted my question and then went wandering off to Google to look for answers. Didn't realize many people had already answered withing a few minutes. Thank you – Hassan Aug 12 '13 at 10:22