Velocity Reviews > conversion of longer int to shorter ones

# conversion of longer int to shorter ones

junky_fellow@yahoo.co.in
Guest
Posts: n/a

 01-12-2007
Hi,

Consider following piece of code:

int i = 0x12345678;
char c;
c = i;
printf("0x%x\n",c);

What value will be printed ?
As per K&R, longer integers are converted to shorter ones by dropping
the higher order bits. So, value printed should be "0x78".

However, my question is that can this value be different on machines
with different endianness ?

thanks a lot for any help ...

=?utf-8?B?SGFyYWxkIHZhbiBExLNr?=
Guest
Posts: n/a

 01-12-2007
http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:
> Hi,
>
> Consider following piece of code:
>
> int i = 0x12345678;
> char c;
> c = i;
> printf("0x%x\n",c);
>
> What value will be printed ?
> As per K&R, longer integers are converted to shorter ones by dropping
> the higher order bits. So, value printed should be "0x78".

In standard C, this is only true for unsigned integer types. On many
implementations this is also true for signed integer types, but if
possible, don't rely on it.

> However, my question is that can this value be different on machines
> with different endianness ?

It is not likely to depend on endianness. If both types are declared as
unsigned, and if the size of the types is what you expect they are
(you're assuming an int is large enough to store 0x12345678, and that
char only has 8 bits), then it would print 0x78 no matter how the value
is stored in memory. However, with signed types, "either the result is
implementation-defined or an implementation-defined signal is raised".
The output could be 0x78. But it's just as possible to have 0xFF
assigned to c, or 0, or to have the program abort.

CBFalconer
Guest
Posts: n/a

 01-12-2007
"(E-Mail Removed)" wrote:
>
> Consider following piece of code:
>
> int i = 0x12345678;
> char c;
> c = i;
> printf("0x%x\n",c);
>
> What value will be printed ?
> As per K&R, longer integers are converted to shorter ones by dropping
> the higher order bits. So, value printed should be "0x78".

Provided that CHAR_BIT is 8.

>
> However, my question is that can this value be different on machines
> with different endianness ?

No.

--
"I have a creative mind. You (singular) are eccentric.
He is insane. We are losing sight of reality.
You (plural) are smoking crack. They are certifiable."
Declension of verbs, per Lewin Edwards

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post trvlDev ASP .Net 3 04-06-2007 08:41 PM Steventangle Perl Misc 4 03-23-2005 06:10 PM Hal Styli C Programming 14 01-20-2004 10:00 PM Richard HTML 2 07-10-2003 05:04 PM Schnoffos C Programming 2 06-27-2003 03:13 AM