QChar stores a negative Latin1 code for multiply sign '×'

224 views Asked by At

I want to get the Latin1 code for multiply sign ×, but when I check the value inside the QChar it has -41'×'.

My code:

QString data = "×";
QChar m = data.at(0);
unsigned short ascii = (unsigned short)m.toLatin1();

When I debug, in the second line I see the QChar value is -41'×'.

I changed the code:

unsigned int ascii = c.unicode();

But I get the value 215 rather and I expect 158.

2

There are 2 answers

0
mfuchs On

The multiply sign × is not an ascii sign, as you can see when checking man ascii if you are on a unix system.

What its value is depends on the encoding, see here for its UTF representations. For example on UTF-8 it has the value 0xC397 which are two bytes. As is mentioned on the unicode page I linked 215 is the decimal value to represent this character in UTF-16 encoding, which is what c.unicode() returns. I don't know why you expect 158.

There is an ascii multiply sign though, which is *.

2
Kuba hasn't forgotten Monica On

If you check the Latin1 code table, it's obvious that × is indeed encoded as 215, or -41. Qt is giving you the correct result.

Your mistakes are:

  1. Assuming that Latin1 is equivalent to ASCII. Latin1 merely contains ASCII, but is the superset: it defines 2x more codes than ASCII does.

  2. Assuming that × is represented in the ASCII. It is not.

I have no clue where you got the idea that Latin1-encoded × should be 158. Surely it didn't come from the Latin1 code table! Incidentally, the Latin1 and UTF-8 encodings of × are identical.