Re: Quick check on signed promotion of bytes



Tomás Ó hÉilidhe wrote:
Eric Sosman:

1) x is promoted to signed int.
2) The complement is take of this signed int.
3) This signed int is then converted to an unsigned char
That's right, under your assumptions. On "exotic" machines
where UCHAR_MAX > INT_MAX (for example, on hardware where all
of char, short, and int are 16 bits wide), then x promotes to
an unsigned int instead of to an int in step 1.


So just to confirm if I'm thinking right. We start off with:

char unsigned x, y;

x = 0xf0;

y = ~x;

What we _want_ this code to do is to give us the value 0x0f for y (i.e. the complement of x). However what _could_ happen is:

1) x is promoted to signed int.

=> Now we have a signed int with the value 0xf0

2) The complement is taken of this signed int.

=> Now we have some other number that is negative. The exact number
depends on the number system in use (e.g. sign-magnitude), and
also the amount of bits in an int.

3) The signed int is converted to an unsigned char.

=> This process is well-defined, but we don't know what signed
value we have.

Therefore, it is my assumption that will not give the desired behaviour on every implementation of the Standard -- we could get something totally different from 0x0f as an answer (even on an 8-bit-byte system).

That sound right?

Sounds right to me. The list of potential negative values
is long but "sparse:" two's complement and ones' complement give
-241 and -240, respectively, while signed magnitude gives one of
-0x7f0f, -0xff0f, -0x1ff0f, ... depending on the number of value
bits in an int.

--
Eric.Sosman@xxxxxxx
.



Relevant Pages

  • Re: How to extract bytes from long?
    ... >> complement, if this representation is a normal value it is called ... and the process by which a negative signed int is transformed into ... a trap representation, now you say it's a valid value?!?" ...
    (comp.lang.c)
  • Re: bits and good habits
    ... as the complement of the SIGNED int 0x02 depends on ... This works even if B is a signed int, as it's converted to unsigned first, ... reducing its value): ...
    (comp.lang.c)
  • Signed 16 bit numbers in AD21161 and VisualDSP
    ... two's complement until it reaches the 32 bit width, ... if represented as a 32 bit signed int. ... How will I manipulate the numbers I got from the SPORTS if they are ... Make the calculations in software for two' ...
    (comp.dsp)
  • Re: Quick check on signed promotion of bytes
    ... Eric Sosman: ... The complement is take of this signed int. ... The signed int is converted to an unsigned char. ...
    (comp.lang.c)
  • Re: C standard question?
    ... char unsigned uc1, uc2; ... The complement is gotten of this signed int ... There's no problem on a two's complement system, ...
    (comp.lang.c)