大小为1的字节序和位域 [英] Endianness and bitfields of size 1

查看:65
本文介绍了大小为1的字节序和位域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为字节序不应影响最多1个字节的大小结构.但是,这是我的小端机器上的代码:

I thought that endianness is not supposed to affect structs of size at most 1 byte. But here's the code on my little endian machine:

#include <iostream>
#include <bitset>
#include <cstdint>
#include <cstring>

using namespace std;

static_assert(sizeof(uint8_t) == 1, "Wrong uint8_t size");

struct Pieces {
    uint8_t flag : 1;
    uint8_t value : 7;
};

static_assert(sizeof(Pieces) == 1, "Something went wrong with Pieces size");

int main()
{
    uint8_t value = 0b10001111;
    Pieces pieces;
    std::memcpy(&pieces, &value, 1);

    cout << bitset<8>(value) << endl;
    // 10001111
    cout << bitset<1>(pieces.flag) << bitset<7>(pieces.value) << endl;
    // 11000111
    return 0;
}

结果不正确.但是,如果我更改 pieces 结构中的 flag value 成员的顺序,则结果是正确的.但这不是我写的那样吗?我期望 value 中的第一位(从左侧开始计数)是该标志.看起来像字节序问题,但是不是应该用字节序来定义字节顺序,而不是位顺序吗?

The result is incorrect. But if I change the order of flag and value members in pieces struct then the result is correct. But isn't it supposed to be as I've written? I'm expecting the first (counting from the left) bit in value to be the flag. It looks like endianess issue but isn't endianess supposed define the order of bytes, not bits?

有人可以告诉我这里到底是怎么回事吗?

Could someone explain to me what's exactly going on here?

推荐答案

所以让我从评论中收集所有信息.

So let me gather all the info from comments.

似乎在标准中未指定位字段的顺序,因此依赖于实现.该标准的相关部分是(由于@molbdnilo):

It seems that the order of bit fields is not specified in the standard and thus is implementation dependent. The relevant part of the standard is (thanks to @molbdnilo):

第9.6节:在某些机器上,位字段是从右到左分配的,在其他机器上是从左到右分配的."

§9.6: "Bit-fields are assigned right-to-left on some machines, left-to-right on others."

也让我注意其他评论.似乎位字段的顺序在内存中只是颠倒了.这似乎也与普通字段的顺序一致,并且可能与字节序一致(如果有人可以在big-endian机器上检查它,我将不胜感激.)

Also let me note other comments. It seems that the order of bit fields is simply reversed in memory. This seems to be consistent with the order of normal fields as well and is probably consistent with endianness (I would appreciate if someone can check it on a big-endian machine).

我想这就是在某些机器上从右到左"和在其他机器上从左到右"的意思.但是,这是我的解释,如前所述,我们不应依赖它.

I guess that's what "right-to-left on some machines" and "left-to-right on others" means. However this is my interpretation and as stated earlier we should not depend on it.

这篇关于大小为1的字节序和位域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆