From mboxrd@z Thu Jan 1 00:00:00 1970 MIME-Version: 1.0 In-Reply-To: <20100616175211.106945B2E@mail.bitblocks.com> References: <20100616175211.106945B2E@mail.bitblocks.com> Date: Thu, 17 Jun 2010 09:50:59 +0200 Message-ID: From: hugo rivera To: Fans of the OS Plan 9 from Bell Labs <9fans@9fans.net> Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Subject: Re: [9fans] portability question Topicbox-Message-UUID: 351f68d2-ead6-11e9-9d60-3106f5b1d025 Thanks for the feedback. 2010/6/16 Bakul Shah : > On Wed, 16 Jun 2010 11:11:09 +0200 hugo rivera =C2=A0w= rote: >> Can someone clarify why the program included outputs 'AB000000' (as I >> expect) on 32 bit systems and 'FFFFFFFFAB000000' on 64 bit systems? >> where all those 1's came from? what's the portable way of doing this? >> sorry for newbie questions like this. >> >> >> =C2=A0 =C2=A0 =C2=A0 =C2=A0unsigned long l; >> =C2=A0 =C2=A0 =C2=A0 =C2=A0 unsigned char c; >> >> =C2=A0 =C2=A0 =C2=A0 =C2=A0 l =3D 0L; >> =C2=A0 =C2=A0 =C2=A0 =C2=A0 c =3D 0xAB; >> =C2=A0 =C2=A0 =C2=A0 =C2=A0 l |=3D c << 24; >> =C2=A0 =C2=A0 =C2=A0 =C2=A0 printf("%lX\n", l); > > For use of C on non-plan9 machines I would recommend > downloading the last draft of the C9x standard as a ready > reference. =C2=A0Google for n843. > > As per Section 6.5.7 of C9x, both operands of << must be of > "integer type" and the result type is that of the left > operand. Since sizeof c < sizeof(int), it is promoted. =C2=A0Now > 6.3.1.2 says "if an int can represent all values of the > original type, the value is converted to an int". So c is > first converted to an int which means c << 24 is an integer > and -ve. Since an int is smaller than a long (in your case) > it is promoted to a long. Changing the |=3D statement to > > =C2=A0 =C2=A0 =C2=A0 =C2=A0 l |=3D (unsigned)c << 24; > > should give you what you want. > > --=20 Hugo