Jack Klein <ja*******@spamcop.net> wrote in message news:<nu********************************@4ax.com>. ..
On 19 Aug 2003 06:22:24 -0700, di****@ix.netcom.com (David Cattarin)
wrote in comp.lang.c++:
"Bob Smith" <la******@yahoo.com> wrote in message news:<6s********************@twister.nyroc.rr.com> ... Hello all, I have a question and I am not sure how I should go about doing
it.
I have two unsigned chars and one int. I want to copy both chars to the
int.
for example if char a was represented binary by 10000110 and char 2 by
10101010
I would like my int to be represented by 1000011010101010 I know short in
would probably be
best but for right now int will work, I may have additions I might need to
add.
Just asssinging the value from char to int will set the LSB correctly. How
can i get the MSB in the
right place?
I am using G++ on a redhat 7.3 system
thanks
If you are doing this a lot, then the best way is to write a helper
class, or to define a union, something like this:
union MyUnion
{
char c[ 2 ];
int i;
};
Depending on the endianness of your system, you'll need to c[ 0 ] or
c[ 1 ] will be the MSB.
Dave
Of course this works in practice on most implementations, but it is
undefined behavior.
Actually, what I posted was just wrong, it really should be this:
union MyUnion
{
char c[ sizeof( int ) ]; // On most systems int is 4 bytes
int;
};
Anyway, aside from the fact that standard does not specify endianness,
nor the size of an int, are there any other areas where the code is
undefined? I don't belive alignment is an issue in this case, but I
could be wrong there. As long as there was a test for endianness,
compile-time or otherwise, and c[ ] was filled correctly, this should
be fairly portable, though I'd be wary of trying it on an embedded
system. Are there any systems where this would be a problem?
In general, I've found that most bit-twiddling code ventures into the
undefined territory and I don't think there is any way around that.
Dave