问题描述
我需要将bit-field结构从little-endian转换为big-endia架构。
什么是最好的方法,因为如果我只是交换结构元素,就会出现字节边界的问题。
I need to convert a bit-field structure from little-endian to big-endia architecture.What is the best way to do that, as there will be issues in byte boundaries, if I simply swap the structure elements.
Ex结构是: / p>
Ex Structure is:
struct {
unsigned int b1:1;
unsigned int b2:8;
unsigned int b3:7;
unsigned int b4:8;
unsigned int b5:7;
unsigned int b6:1;
};
推荐答案
要做到这一点,我终于得到了一个解决方案从上述解决方案中得出的解决方案)。这是如果我从x86转换到Solaris SPARC。
To get this going I finally got a solution (some what derived from epatel's solution above). This is if I convert from x86 to Solaris SPARC.
我们需要先交换传入的结构,然后以相反的顺序读取元素。
基本上看看结构是如何排列的,我看到字节顺序和位排序都改变了endianess。这是一个伪代码。
We need to first swap the incoming sturcture and then read the elements in reverse order.Basically after looking at how the structures are alligned I saw that the endianess changed both in byte ordering and bit ordering. Here is a pseudo code.
struct orig
{
unsigned int b1:1;
unsigned int b2:8;
unsigned int b3:7;
unsigned int b4:8;
unsigned int b5:7;
unsigned int b6:1;
};
struct temp
{
unsigned int b6:1;
unsigned int b5:7;
unsigned int b4:8;
unsigned int b3:7;
unsigned int b2:8;
unsigned int b1:1;
}temp;
func (struct orig *toconvert)
{
struct temp temp_val;
//Swap the bytes
swap32byte((u32*)toconvert);
//Now read the structure in reverse order - bytes have been swapped
(u32*)&temp_val = (u32 *)toconvert;
//Write it back to orignal structure
toconvert->b6=temp_val.b6;
toconvert->b5=temp_val.b5;
toconvert->b4=temp_val.b4;
toconvert->b3=temp_val.b3;
toconvert->b2=temp_val.b2;
toconvert->b1=temp_val.b1;
}
经过一些实验,我发现这种方法只有在元素完全填充结构时才有效,即没有未使用的位。
After some experimenting I found that this approach is only valid if the elements completely fill the structure, i.e. there are no unused bits.
这篇关于在一个字段结构中转换Endianess的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!