1

Can an unsigned type always store the value of a signed type and vice versa? I mean not by arithmetic value but rather as "raw value".

Example:

// Generic Integer (without sign saved)
typedef uintmax_t generic_int;

int16_t p = -17;
// Store int16_t in a generic int
generic_int myint = (generic_int)p;

Later on...

// Get the signed value again
int16_t plater = (int16_t)(myint & 0xFFFFULL);

Is this always safe? Will the correct value of the original signed variable be restored in all cases?

MatthewD
  • 2,509
  • 2
  • 23
  • 27
Marco
  • 7,007
  • 2
  • 19
  • 49
  • What does "safe" mean? Does it mean anything? – Kerrek SB Sep 20 '14 at 12:51
  • I mean by safe that the signed value from the generic integer always will be the same at the end regardless of the implementation. – Marco Sep 20 '14 at 12:52
  • Does this answer your question? http://stackoverflow.com/questions/5040920/converting-from-signed-char-to-unsigned-char-and-back-again/ – mafso Sep 20 '14 at 13:12
  • 3
    No, conversion from unsigned to signed is not safe. If the value is too large to fit into the target type, the result is implementation-defined. – n. m. could be an AI Sep 20 '14 at 13:32
  • @n.m. Technically yes, but how should conversion be defined differently? On a 2's complement machine, I can hardly think of any other reasonable definition. – mafso Sep 20 '14 at 13:37
  • 1
    @mafso Clamping to `INT_MAX` comes to mind. – Sneftel Sep 20 '14 at 14:01
  • @Sneftel: Yes, or raising a signal. But that disallows e.g. `(char)getchar()`, which a compiler should support IMO (for signed `char` and on a 2’s complement machine). The portable workaround would be something along `int tmp = getchar(); char c = !CHAR_MIN || tmp – mafso Sep 20 '14 at 14:08
  • @mafso Things get weird even on twos complement machines if they have padding bits or trap values. – Raymond Chen Sep 20 '14 at 14:27
  • I believe that the following round-trip conversion is standard compliant: Store: `generic_int = reinterpret_cast(p);` Load: `reinterpret_cast(p) = generic_int;`. The widths guarantee that the unsigned value can be represented, and aliasing a signed and an unsigned value is allowed. You should not assume any particular meaning of the stored value. – Kerrek SB Sep 20 '14 at 18:30
  • @mafso I'm saying what the standard says, if you want to go beyond that that's fine. – n. m. could be an AI Sep 20 '14 at 18:36

0 Answers0