Type-punning / casting problem

J

James Kanze

as the program is about to deal with changing the
representation(endians) of a number,I see little chance for
portabality .

I disagree. Inside the program, you have a value; you're not
concerned with representation. You want to generate a specific
representation for that value. I fail to see where that should
cause any portability problems: if the specification of the
target representation says that the first byte contains the bits
24-31 of that value, then you extract the bits 24-31 from the
value, and put them in the first byte. C++ has bitwise
operators, which allow doing that portable. (C++ also defines
the conversion of signed to unsigned in such a way that the
resulting unsigned value corresponds to the bit pattern of the
signed value in 2's complement arithmetic. So if the
specification requires 32 bit 2's complement, high byte first
(i.e. XDR):

void
writeInt(
std::eek:stream& binaryStream,
int value )
{
uint32_t tmp = value ;
binaryStream.put( (tmp >> 24) & 0xFF ) ;
binaryStream.put( (tmp >> 16) & 0xFF ) ;
binaryStream.put( (tmp >> 8) & 0xFF ) ;
binaryStream.put( (tmp ) & 0xFF ) ;
}

Guaranteed to generate the specified external representation,
independently of the internal representation. On *all*
conformant implementations.
We are just looking for a program that works.

You mean like the above.

Quite frankly, I don't see any reason to use non-portable code,
when there is a portable solution which is far clearer and more
explicit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,219
Latest member
KristieKoh

Latest Threads

Top