C ++ - Invalid ASCII value ("ë")

Firstly, I apologize for any English mistakes that I make, but being 15 and French doesn't help ...

I am trying to program a PNG decoder using the file format specification ( http://www.libpng.org/pub/png/spec/1.2/PNG-Contents.html ), but I ran into a weird problem.

The specification states that the first eight bytes of the PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10.

When I test this simple program:

int main() 
{
    ifstream file("test.png");

    string line;
    getline(file, line);

    cout << line[0] << endl;
}

The output is ë, which represents 137 in the ascii table. Well, it matches the first byte.

However, when I do int ascii_value = line[0];, the output value is -119, which is not the correct ascii value.

"e", ascii.

- , ? , ascii, .

! char !

+5
6

char , .

:

const unsigned char value = (unsigned char) line[0];

, -119 = 137 , , -, . , , .

+10

char ++ , 1) . ( ) , , :

a > 128 . -119 137. , :

unsigned char c = 137;
assert(static_cast<signed char>(c) == -119);

, , .


1) signed char, unsigned char.

+5

ASCII 0.. 127. ASCII 137.

, " ASCII". ( ) ASCII. Heck, Unicode " ASCII".

-119, char , -128 127. (-119 - 137 - 256). , unsigned char:

int value = static_cast<unsigned char>(line[0]);
+4

, . ASCII ( ).

-119 0x89. 137 0x89.

Try

int ascii_value = line[0] & 0x00FF;

int ascii_value = (unsigned char)line[0];
0

137 = -119 = 0 × 89. (unsigned) (unsigned char)(line[0]), 137.

char ( std::string) - [] , -128-127. 127 .

0

C ++ does not indicate whether a charsigned or unsigned type. This means that “extended” ASCII characters (outside the range 0..127 with their upper bit set) can be interpreted as negative values; and this is similar to what your compiler does.

To get the unsigned value you expect, you need to explicitly convert it to type unsigned char:

int ascii_value = static_cast<unsigned char>(line[0]); // Should be 137
0
source

All Articles