简体   繁体   中英

Need for unusual string concatenation in C or C++ for microcontroller display driver

I'm adding string and text support to Dean Reading's " SevSeg " display driver for 7-segment displays , controlled by Arduino, and I need some help.

Due to limitations on the display, I have to create special cases where two digits on the display are used to display one character. Ex: "M" must be treated as a special case since one display digit cannot create an M by itself.

What I need essentially is for the user to be able to write something like this:

char myString[] = "Help Me Do This!";

Except that I want them to be able to specify whether they want to use the special M (called "PSEUDO_M") instead. If they leave the above phrase as-is, the M will be replaced with a dash, and I don't want to prohibit this behavior since the user may want the phrase to fit in a set # of display digits more than they want a 2-digit M. Anyway, what I want is something like this:

const char PSEUDO_M = -128;

char myString[] = "Help " + PSEUDO_M + "e Do this!";
//OR perhaps:
char myString[] = "Help [PSEUDO_M]e Do this!"; 

I would then process their input string, treating the PSEUDO_M (dec -128) as a special case.

Obviously, the above additions of strings doesn't work in C.

I know that a string is simply a char array, so when a user creates a string, the character decimal representation for the above (WITH the PSEUDO_M [-128] used in place of the M [77]) would be:

char myString[] = {72, 101, 108, 112, 32, -128, 101, 32, 68, 111, 32, 84, 104, 105, 115, 33, 0};

However, the above number array is not human-readable. *The idea is that the user types in a string literal essentially, using standard characters. So, what's the best way to write a macro, function, or something else that will easily allow someone to type a phrase to be used in a string, but where M's (dec 77) will be replaced with PSEUDO_M's (dec -128), if the user desires it?*

Note: ideally, the technique I use will not take up any extra bytes in the char array, since my PSEUDO_M could simply be represented as a single character (dec -128).

Note that in C, multiple character literals in sequence are concatenated by the compiler; for example, "foo" "bar" is the same as "foobar" .

Using this and a define, you can get a syntax that's human readable while still having zero runtime overhead.

#define PSEUDO_M "\xAB" // Replace AB with the appropriate code

char myString[] = "Help " PSEUDO_M "e Do this!";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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