C programming help ....
Vu Pham
vu
Fri May 19 23:15:09 PDT 2006
I think gcc will take care of the big/little endian accordingly. Your
solution is correct, too.
I also see somebody use something like :
#define INT(x) (x[3]<<24) + (x[2]<<16) + (x[1])<<8) + x[0]
int a = INT("ABCD");
Sorry for the top post, but Outlook is out of my control :)
________________________________
From: linux-users-bounces at linux-sxs.org
[mailto:linux-users-bounces at linux-sxs.org] On Behalf Of Kevin O'Gorman
Sent: Friday, May 19, 2006 12:05 PM
To: Linux tips and tricks
Subject: Re: C programming help ....
Vu Pham's solution depends on the specifics of your C compiler.
Mine won't allow multi-character constants in that way, at least
not without a warning. It doesn't like his main() function parameters
either.
A more portable way (though still subject to differences of endianness):
typedef union {
char bytes[4];
int code;
} code_t;
int main( int argc, char *argv[] )
{
code_t b = {'A', 'B', 'C', 'D'};
printf(" %02x", (b.code >> 24) & 0xFF);
printf(" %02x", (b.code >> 16) & 0xFF);
printf(" %02x", (b.code >> 8) & 0xFF);
printf(" %02x\n", (b.code ) & 0xFF);
return 0;
}
On 5/19/06, Vu Pham <vu at sivell.com> wrote:
You can use something like
Var = 'LNDE';
And the compiler will pack it in accordingly;
int main( int c, char *args )
{
int a = (int)'XYZT';
printf( "%02x ", (a&0xFF000000) >> 24 );
printf( "%02x ", (a&0x00FF0000) >> 16 );
printf( "%02x ", (a&0x0000FF00) >> 8 );
printf( "%02x \n", (a&0xFF) );
}
[vu at cvs vu]$ ./t
58 59 5a 54
[vu at cvs vu]$
-----Original Message-----
From: linux-users-bounces at linux-sxs.org
[mailto: linux-users-bounces at linux-sxs.org
<mailto:linux-users-bounces at linux-sxs.org> ] On Behalf Of Ben Duncan
Sent: Friday, May 19, 2006 10:52 AM
To: Linux tips and tricks
Subject: C programming help ....
Ok, I am trying to figure out how to "pack" hex strings a 32 bit
integer.
What I need to do is code the following characters.
"LNDE", "INDE", "RNDE", "DATA", "DEAD" each into a integer.
is the correct way to do this (on a 32 bit machine) thus:
int LNDE_int = 0x4C4E4445 ; /* Pack 'LNDE' into LNDE_int */
.. and so on and so on ....
Thanks ...
_______________________________________________
Linux-users mailing list ( Linux-users at linux-sxs.org )
Unsub/Password/Etc:
http://mail.linux-sxs.org/cgi-bin/mailman/listinfo/linux-users
Need to chat further on this subject? Check out #linux-users on
irc.linux-sxs.org !
--
Kevin O'Gorman, PhD
More information about the Linux-users
mailing list