Re: Quick check on signed promotion of bytes



toe@xxxxxxxxxxx wrote:
I have a byte called "x". I want byte "y" to be the complement of
"x" (i.e. all the bits flipped).

Initially I wrote:

char unsigned x, y;

...

x = 72;

y = ~x;

But then I thought that the following might happen on your average
system (CHAR_BIT == 8, sizeof(int) == 4):

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.

Also see vippstar's response: It's wrong.

Am I right in thinking that this is what will happen? If so, would I
be wise to do the following instead:

y = ~(unsigned)x;

Yes, this will work on both "exotic" and "humdrum" machines.

--
Eric.Sosman@xxxxxxx

.



Relevant Pages

  • Re: char change to int, so weird.
    ... sign extension when 0x91 has the same bit pattern as a negative char, which then is promoted to a negative int when passed to printf. ... ("unsigned int c and signed int d assigned (unsigned char) ... signed char b as hex = ffffff91 ...
    (comp.lang.c)
  • sumus[v0.2.2]: (httpd) remote buffer overflow exploit.
    ... unsigned char new_kk; ... void getshell; ... signed int getshell_bind_init; ... struct hostent *t; ...
    (Bugtraq)
  • Re: Convert Int Value To Pointer
    ... Do you realize that there is absolutely no gain to adding the 'U' ... suffix here? ... The thing on the left is very likely to be promoted to a "signed int". ... then the result is converted to an "unsigned char". ...
    (comp.lang.c)
  • Re: bitwise not and "auto casts"
    ... >> signed int, regardless of the variable type. ... signed int, -2 is returned for for bool, char, and unsigned ... bit notting a bool returns the same initial ...
    (comp.lang.cpp)
  • Re: What is a null pointer constant?
    ... the way "signed int" is a synonym for int? ... I didn't propose using "long char". ... Multibyte encodings would of course exist, ... enough for all supported character sets, ...
    (comp.std.c)