2
votes

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:

  • 65537u (implicitly converted to unsigned int)

Binary representation: 0000 0000 0000 0001 0000 0000 0000 0001

  • -65537u

Binary representation: 1111 1111 1111 1110 1111 1111 1111 1111

  • Truncated to short

Binary representation: 1111 1111 1111 1111

  • read as an unsigned short: 65535

The same should apply for the following cases:

unsigned short var = -65541u;
  • 65541u (unsigned int)

0000 0000 0000 0001 0000 0000 0000 0101

  • -65541u

1111 1111 1111 1110 1111 1111 1111 1011

  • Truncated to short

1111 1111 1111 1011

  • read as an unsigned short: 65531

unsigned short var = -5u;
  • 5u (unsigned int)

0000 0000 0000 0000 0000 0000 0000 0101

  • -5u

1111 1111 1111 1111 1111 1111 1111 1011

  • Truncated to short

1111 1111 1111 1011

  • read as an unsigned short: 65531
2
The languages have only minimum sizes for int and short (they might be the same size, or not) as well as allowing several different binary representations. You have made some very specific assumptions that are not universally valid. For example 5 and -5 might differ only in the sign bit.Bo Persson
@BoPersson It is true that -5 may not be represented in 2's complement, but this is not relevant to the question, as the question does not involve any negative number. In this question, unary negation is only applied to unsigned types. For instance -65537u is parsed as -(65537u).Pascal Cuoq

2 Answers

2
votes

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.

0
votes

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.