3

Possible Duplicate:
How do promotion rules work when the signedness on either side of a binary operator differ?

When casting from an unsigned integer to a signed integer, I know the represention of the variable's bits changes. For instance, 255 may become -1, when converting from uint8 to int8. However, I was never sure what a 'cast' or 'conversion' entailed for the underlying bits themselves.

My question is, is the raw bit pattern of an integer variable guaranteed to remain the same after a static_cast between signed and unsigned types, or is it possible that it be transformed by the cast in some way?

Out of curiosity too, does a static_cast between integer signage types generate assembly, or is it used only so the compiler knows what asm instructions to generate?

edit:

Here's an example of the kind of scenario I would want to know about:

unsigned int uintvar = random();
unsigned int control = uintvar;
assert(control == static_cast<unsigned int>(static_cast<signed int>(uintvar)));

Ignoring the fact the double cast would get optimized away, would this example be guarenteed to always hold true?

Community
  • 1
  • 1
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • 6
    Actually, nothing changes. – Mysticial Jan 21 '13 at 22:15
  • 4
    Well, if the representation of signed integers is not two's complement, and you cast a negative value to an unsigned type, then the bit-pattern does actually change. – Daniel Fischer Jan 21 '13 at 22:17
  • @DanielFischer dammit Daniel, I'm out of up-votes on comments for another 2 hours =( +1 to that. – WhozCraig Jan 21 '13 at 22:24
  • I'm getting some mixed signals, aha. Is there anything I can add to clarify the question maybe? – Anne Quinn Jan 21 '13 at 22:44
  • Clairvoire - nothing changes if the bit representation is two's compliment. I don't know of any even remotely mainstream systems which do not use two's compliment, but it's not mandated by the standard, so what DanielFischer's answer is getting at is that it *could* change. – sapi Jan 21 '13 at 22:52

2 Answers2

8

The bit pattern doesn't change at all (on most architectures you're likely to encounter in practice). The difference is in the instructions generated by the compiler to manipulate the values.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
4

If the unsigned value is too large to fit inside the signed counterpart then it's undefined behavior.

255 becomes -1 because those bits are -1 in two's compliment. Nothing happens with the bits.

Pubby
  • 51,882
  • 13
  • 139
  • 180