How can I convert (int) to (unsigned int) while saving the original bit pattern?

Suppose we define:

short x = -1;
unsigned short y = (unsigned short) x;

In accordance with standard C99:

Otherwise, if the new type is unsigned, the value is converted to repeatedly adding or subtracting one greater than the maximum value that can be represented in the new type until the value is in the range of the new type. (ISO / IEC 9899: 1999 6.3.1.3/2)

So, assuming two bytes for short and a two-component representation, the bit patterns of these two integers are:

x = 1111 1111 1111 1111 (value of -1),
y = 1111 1111 1111 1111 (value of 65535).

-1 short, , , 65535, 65536 - 1, 65535, . , int , .

, , . " ,..." (ISO/IEC 9899: 1999 6.2.6.2/2)

, , x 1111 1111 1111 1110 , , , x 1000 0000 0000 0001. -1, short, 65536, . 1111 1111 1111 1111.

, int unsigned int .

, int unsigned int, -, , . , , .

, - ? , int ? , int unsigned int?

, int unsigned int , - . , int int N _t :

unsigned short y = (unsigned short)(int16_t) x;

, , ! , , - . , int unsigned int, , @Leushenko . , , .

+4
2

(int) (unsigned)(intN_t) ?

, C . C , .

, x, int, unsigned intN_t, . , x .

C , / " + 1" , . , .

- , OP.

C , : 0 . IOWs INT_MAX == UINT_MAX. int unsigned int .


, union unsigned char.

union uA {
  some_signed_int_type i;
  unsigned char uc[sizeof (some_signed_int_type)];
}

( ), , , . , , . , .

assert(uintN_MAX > some_signed_type_max);
union uB {
  some_signed_int_type i;
  uintN_t u;
}

unsigned char (u)intN_t , , .

+1

, , -:

union S2US { short from; unsigned short to; };

...
short value = ...
unsigned short bits = (union S2US){ .from = value }.to;
...

95 ( 6.5.2.3): " , , , , , , 6.2.6". - , - , .

(6.2.5 p6), (6.7.2.1 p16), , , .

+4

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


All Articles