我在位域和字节序方面遇到了一些麻烦...... 我很困惑。
我需要解析一些从网络获取的数据,发送的是 lil endian(我使用的是 boost::asio)
你能解释一下吗
struct TEST
{
unsigned short _last : 1;
unsigned short _ID : 6;
unsigned short _LENGH : 9;
};
struct TEST2
{
unsigned short _LENGH:9 ;
unsigned short _ID:6 ;
unsigned short _last:1 ;
};
int main(int argc, char* argv[])
{
printf("Hello World!\n");
TEST one;
one._ID = 0;
one._last = 0;
one._LENGH = 2; //the value affected here is always divided by 2, it is multiplied by 2 when i cast a short to this structure
TEST2 two;
two._ID = 0;
two._last = 0;
two._LENGH = 2; //the value here is well stored
bit_print((char*)&one,2);
bit_print((char*)&two,2);
return 0;
}
[输出]
00000000 00000001
00000010 00000000
最佳答案
为什么说第二个值“存储得好”?查看您自己的输出:如果 two
中的第一个字段 (_LENGTH
) 应该由 9 位组成,那么第二个输出也不正确。它应该是 00000001 00000000
,但你却得到了 00000010 00000000
,这意味着在 two
中,你的值“乘以”了 2。
我猜你的 bit_print
坏了,打印了一些废话。
(强制免责声明:位域布局是实现定义的。当您使用位域时,不保证任何与 C++ 语言布局相关的内容。)
关于c++ - 为什么我的值被位域除以 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3637757/