views:

650

answers:

5

I have a special unsigned long (32 bits) and I need to convert the endianness of it bit by bit - my long represents several things all smooshed together into one piece of binary.

How do I do it?

A: 

Are you starting from "Big-Endian" or "Little-Endian?" Could you provide some context for your problem and possibly sample code to help us understand your question better?

You may find this resource helpful for discussion and examples for Endian conversion:

http://sites.google.com/site/insideoscore/endianness

Thanks, -bn

bn
+1  A: 

Endianness is a word-level concept where the bytes are either stored most-significant byte first (big endian) or least-significant byte first (little endian). Data transferred over a network is typically big endian (so-called network byte order). Data stored in memory on a machine can be in either order, with little endian being the most common given the prevalence of the Intel x86 architecture. Even though most computer architectures are big endian, the x86 is so ubiquitous that you'll most often see little endian data in memory.

Anyhow, the point of all that is that endianness is a very specific concept that only applies at the byte level, not the bit level. If ntohs(), ntohl(), htons(), and htonl() don't do what you want then what you're dealing with isn't endianness per se.

If you need to reverse the individual bits of your unsigned long or do anything else complicated like that, please post more information about what exactly you need to do.

John Kugelman
A: 

Can you explain this further? Are you trying to reverse the bits within bytes or simply reverse the byte order (typical in networking, going from "host byte order" to "network byte order"). It sounds like all you really want is the typical case. If you provide more info, I can edit and privide a better answer.

BobbyShaftoe
+1  A: 

Be careful to understand the meaning of 'endianness'. It refers to the order of bytes within the data, not bits within the byte. You may only need to use a function like htonl or ntohl to convert your d-word.

If you truly want to reverse the order of all bits in the 32b data type, you could write an iterative algorithm to mask and shift each bit into the appropriate reflected position.

Adam
A: 

A simple endianess conversion function for an unsigned long value could look like the following:

typedef union {
  unsigned long u32;
  unsigned char u8 [ 4 ];
} U32_U8;

unsigned long SwapEndian(unsigned long u)
{
   U32_U8 source;
   U32_U8 dest;

   source.u32 = u;
   dest.u8[0] = source.u8[3];
   dest.u8[1] = source.u8[2];
   dest.u8[2] = source.u8[1];
   dest.u8[3] = source.u8[0];

   return dest.u32;
}
semaj