Anne Quinn
Anne Quinn

Reputation: 13040

C++: insert a negative character value into a string literal?

I have a text renderer that uses negative char values from strings to render custom symbols in a font I made, instead of regular ascii text.

text.write("Hello! _"); // insert a heart at the underscore somehow...
                        // the heart's value is char -10

Is there anyway to get a negative char value, written statically inside the double quotes? Or is there a way to do this outside of the quotes, but still as a string literal?

Edit:

To clarify a little, I have to use a char array in this particular case unfortunately. The code internally uses std::string, and all the positive values are taken by standard ascii glyphs. My goal is to be able to inject a negative number to represent extra symbols, into a string literal. So the following would be true:

const char * literal = "a literal w/ a negative char value as the 10th element"
literal[9] == -10; // would be true

Upvotes: 3

Views: 1842

Answers (2)

zch
zch

Reputation: 15278

You can write "Hello! \xf6". f616 = -10 + 256

This works, because in 8-bit 2-complement integers negative values -128 .. -1 have the same bit representations as 256 bigger unsigned values 128 .. 255.

Upvotes: 4

RedXIII
RedXIII

Reputation: 831

I think you did not get the point how positive and negative integers are represented in memory.

Each "unsigned char" > 127 will be interpreted as a "signed char" < 0, i.e. when you use characters which are not in the ASCII-Set and interpret them as a signed char, they are automatically negative.

So I see two general approaches for you to enter "negative" character values:

  • Either you enter characters from another charset which extend the ASCII-Charset and are fixed to one byte per character, e.g. "ISO-8859-1". Not a good choice in my opinion as you run intro troubles when the file encoding is not set properly, but that should do the trick.
  • Or you use the escape sequences to define the byte directly, e.g. you enter some "unsigned char" >= \x80.

Some references for you:

Upvotes: 1

Related Questions