The C standard indicates this for unsigned types:
A calculation involving unsigned operands can never be overflowed, since a result that cannot be represented by an unsigned integer type is equal to a reduced modulus number, which is one greater than the largest value that a result type can represent.
In this case, if your unsigned char
is 8 bits, this means that the result will be reduced modulo 256, which means that if b
was 0x55
, a
would actually be in the form 0xAA
.
But keep in mind that if an unsigned char
wider than 8 bits (which is completely legal), you will get a different result. To ensure that you can get 0xAA
as a result, you can use:
a = ~b & 0xff;
(Bitwise and should be optimized on platforms where unsigned char
is 8 bits).
Note also that if you use a signed type, the result is determined by the implementation.
source share