C Endian Conversion : bit by bit

2019-06-14 18:19发布

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?

4条回答
乱世女痞
2楼-- · 2019-06-14 18:52

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.

查看更多
We Are One
3楼-- · 2019-06-14 19:07

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;
}
查看更多
SAY GOODBYE
4楼-- · 2019-06-14 19:10

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-06-14 19:13

To invert the bit order of an integer, you can shift out the bits in one direction and shift the bits to the destination in the opposite direction.

查看更多
登录 后发表回答