lovehell
lovehell

Reputation: 169

Two's complement in C

Let's suppose a 16-bits variable (a) stored as unsigned 16-bits. If I cast to signed 16-bits can I say that I read my signed number (b) as two's complement format ?

uint16_t a = 0xFFF1;
int16_t b;
b = (int16_t)a;

Upvotes: 2

Views: 1973

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60143

Practically yes. All common architectures should be two's-complement and treat same-width unsigned-to-signed conversions as basically a no-op.

Theoretically not always. The C standard says that conversions to non-_Bool types do not change values if the values fit (6.3.1.3p1), otherwise for an unsigned-to-signed conversion you either get an implementation defined conversion or a signal is raised (6.3.1.3p3).

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)

3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

(Conversions to _Bool are done by comparison to 0(6.3.1.2p1). There's also no change if the source fits (0 or 1), but all nonzero numbers convert to (_Bool)1, whereas if the wraparound rule (6.3.1.3p2) applied, then even numbers would convert to (_Bool)0, but they don't.)

As Jens Gustedt has noted in the comment, C2x should be removing the special case, and so the practically yes should become always yes.

Upvotes: 6

Related Questions