Difference between signed and unsigned data types?

main() { char i=255; printf("\n%x\n",i); } 

output: ffffffff

 main() { u_char i=255; printf("\n%x\n",i); } 

output: ff

What's going on here? Please explain me the result with good links. This is a very simple thing, I think, and I'm really confused ...

+6
source share
4 answers

What you see here is caused by two things:

  • 255 not in the char range (note that it is implementation-defined, whether char equivalent to signed char or unsigned char , but obviously on your platform it is signed char ). The resulting behavior is determined by the implementation, but it usually wraps around and becomes -1; see two additions .
  • whole promotion because printf() is a variable-argument function. Arguments of an integral type (for example, char ) are automatically raised to int .

So printf() sees an int with a value of -1 and accordingly displays its hexadecimal representation.

There is no wrapper for the unsigned case. printf() sees an int with a value of 255 and accordingly displays its hexadecimal representation (omitting leading zeros).

+10
source

The C compiler must extend the value passed to printf (this is called "promotion"), because printf is a variational function (it can be called with different arguments). For char values, the advanced value is int . Because your char compiler type seems to be signed, the advanced value is a sign extension. In binary format:

 char i = 255 // or: 11111111 in binary int promoted_i = -1 // or: 11....11111 (usually, 32 or 64 ones) 

In the unsigned case, the sign does not expand:

 char u = 255 // or: 11111111 in binary, same as above but with different interpretation unsigned int pu = i // or: 00....0011111111 (8 ones, preceded by the appropriate number of zeroes) 
+4
source

char i = 255; calls the behavior defined by the implementation by converting the value to a signed type that it does not fit into (it is assumed that char is only 8 bits and plain char is signed, both of which are also implementation specific.

0
source

When you set an 8-bit signed variable to a value of 255 that it cannot hold, it looks like in this case it sets the negative (high-end) flag to 1, so the value will be -1 if it was signed, but then it converts to the integer -1, which is ffffffff .

0
source

Source: https://habr.com/ru/post/886096/


All Articles