Johnny Pauling
Johnny Pauling

Reputation: 13387

unsigned/signed short/int conversion

I'm studying signed-unsigned integer conversions and I came to these conclusions, can someone tell me if this is correct please

unsigned short var = -65537u;

Steps:

Binary representation: 0000 0000 0000 0001 0000 0000 0000 0001

Binary representation: 1111 1111 1111 1110 1111 1111 1111 1111

Binary representation: 1111 1111 1111 1111


The same should apply for the following cases:

unsigned short var = -65541u;

0000 0000 0000 0001 0000 0000 0000 0101

1111 1111 1111 1110 1111 1111 1111 1011

1111 1111 1111 1011


unsigned short var = -5u;

0000 0000 0000 0000 0000 0000 0000 0101

1111 1111 1111 1111 1111 1111 1111 1011

1111 1111 1111 1011

Upvotes: 2

Views: 6430

Answers (2)

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

Your analysis is correct for the usual platforms where short is 16 bits and int is 32 bits.

For some platforms, the constant 65537 may not fit in an unsigned int, but if that is the case, 65537u will be typed as a larger unsigned type. The list of types that are tried can be found in section 6.4.4.1:5 of the C99 standard. In C99 it will at least fit in an unsigned long, which is guaranteed by the standard to allow values that large.

The reasoning remains much of the same if that happens, until the conversion back to unsigned short for the assignment.

Conversely, unsigned short is allowed by the C99 standard to hold more than 16 bits. In this case var receives USHRT_MAX-65536 for your first example and similarly for the other ones.

Upvotes: 2

Myforwik
Myforwik

Reputation: 3588

The size of short is implementation dependant - not 16bit. 16bit is the minimum size.

Similairly the size of an int may only be 16bit also.

Upvotes: 0

Related Questions