c question

john at viper.UUCP john at viper.UUCP
Mon Feb 16 13:11:08 AEST 1987


In article <131 at tahoma.ARPA> fawcett at tahoma.ARPA (John Fawcett) writes:
 >... The code I used was:
 >
 >main()
 >{
 >	union
 >	{
 >		char full_message;
 >		int _message;
 >	}u;	
 >
 >	u.full_message = 0xaa;
 >
 >	printf("%10x\n", (int)u.full_message);
 >	printf("%10x\n", u._message);
 >}
 >
 >What I got when I ran this was:
 >
 >  ffffffaa
 >  aa000000
 >
  ....................... 
 >Does anyone know what I am doing wrong, or help me to understand why I got
 >this response.
 >
 >John W. Fawcett				Voice: (206) 237-5080
 >Boeing Commercial Airplane Company	UUCP: ..!uw-beaver!ssc-vax!shuksan
 >P.O. Box 3707, M/S 66-04			!tahoma!fawcett
 >Seattle, WA  98124-2207

  I think I can explain.
  Chars on the compiler you're using are defaulting to signed-char.  If you
change the union as follows, it should solve what I think yu mean by "the
problem":

	union
		{
		unsigned char full_message;
		int	      _message;
		} u;

  The cause of all the extra FF's you got was sign extension.  The 0xaa was
taken to mean -86 when it got tossed into the (signed) char variable.  When
this got cast as an int, it was sign extended to maintain the -86 value.
  The aa000000 was a result from using a union.  The union you created is
4 bytes long.  When you place a char in the first byte, and then read it
back as an int, you get the value given because your machine stores int
values with high order byte first.  On a different machine, you might get
000000aa  or even  0000aa00  for the 2nd value depending on the specific
machine you use.
  Hope this answers your question...
  If not, I guess I didn't understand your question.



More information about the Comp.lang.c mailing list