Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!utgpu!water!watnot!watmath!clyde!rutgers!dayton!viper!john From: john@viper.UUCP Newsgroups: comp.lang.c Subject: Re: c question Message-ID: <536@viper.UUCP> Date: Sun, 15-Feb-87 22:11:08 EST Article-I.D.: viper.536 Posted: Sun Feb 15 22:11:08 1987 Date-Received: Mon, 16-Feb-87 19:40:42 EST References: <131@tahoma.ARPA> Reply-To: john@viper.UUCP (John Stanley) Organization: DynaSoft Systems Lines: 53 Keywords: char, casting, printf Summary: Ever hear of signed char?? In article <131@tahoma.ARPA> fawcett@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.