简体   繁体   English

使用struct中的位字段并使用C ++从内存中读取实例

[英]Using bit fields in struct and reading an instance from Memory with C++

unsigned __int16 var16bit= 6545; //00011001 10010001
unsigned __int8 var8bit;
memcpy(&var8bit, &var16bit, sizeof(var8bit));
cout << var8bit; // result is 145 which is 10010001

When working with little endian machine, lsb is written to memory first then offset is added to address if necessary. 在使用低端字节序计算机时,首先将lsb写入内存,然后在需要时将offset添加到地址。 In this example a 16bit integer is copied to 8bit integer and it losts its msb side because of target space is not enough. 在此示例中,将16位整数复制到8位整数,并且由于目标空间不足而丢失了它的msb端。 Reverse behaviour happens in big endian machines. 反向行为发生在大字节序机器中。

There is another example below 下面还有另一个例子

here is my structure 这是我的结构

struct Account 
{
   unsigned int dollar : 4;
   unsigned int euro : 4;
   unsigned int pound : 4;
   unsigned int ruble : 4;
};

int _tmain(int argc, _TCHAR* argv[])
{
    Account myWealthyAccount = {};
    myWealthyAccount.dollar = 2; // 0010
    myWealthyAccount.euro = 3; // 0011
    myWealthyAccount.pound = 4; // 0100
    myWealthyAccount.ruble = 5; // 0101

    unsigned __int16 sum;
    memcpy(&sum, &myWealthyAccount, sizeof(myWealthyAccount));
    cout << sum;
    // result is 0101010000110010  ruble pound euro dollar
    unsigned __int8 sum8Bit;
    memcpy(&sum8Bit, &myWealthyAccount, sizeof(sum8Bit));
    cout << sum8Bit; // result is 50 which is 0011 0010 euro dollar

    return 0;
}

0101010000110010 ruble pound euro dollar 0101010000110010卢布英镑欧元美元

Why was it ordered as ruble pound euro dollar why not the opposite way? 为什么以卢布英镑订购欧元而不是相反方式?

Why is ruble is beside msb and dollar is beside lsb? 为什么卢布在msb旁边而美元在lsb旁边?

Is this about being little endian or big endian machine? 这是关于小的字节序还是大字节序的机器? Or Is this about Struct? 还是这是关于Struct的? Is this about compiler? 这是关于编译器的吗?

If I run this example in big endian machine, what result would occur? 如果我在大型字节序计算机中运行此示例,将发生什么结果? Why? 为什么?

I'm open to every advises like articles, videos, websites about the topic. 我愿意接受有关该主题的文章,视频,网站等所有建议。

Thanks 谢谢

"Why was it ordered as ruble pound euro dollar why not the opposite way?" “为什么要订购卢布英镑,为什么不是相反?”

I copied your code and got the exact same result. 我复制了您的代码并获得了完全相同的结果。 On your first example the 16 bit integer is stored like that 00011001 10010001. So if you take only the lsb you get 10010001. But your Bitfield is stored like 0101 0100 0011 0010. 在第一个示例中,将16位整数存储为0001100110010001。因此,如果仅使用lsb,则将获得10010001。但是,您的位域存储为0101 0100 0011 0010。

If you look on http://en.cppreference.com/w/cpp/language/bit_field under notes: "Also, on some platforms, bit fields are packed left-to-right, on others right-to-left" . 如果您在http://en.cppreference.com/w/cpp/language/bit_field上注意以下内容: “此外,在某些平台上,位字段从左到右打包,在其他平台上,则从右到左打包” So it is implementation defined which order you have. 因此,实现定义了您拥有的订单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM