简体   繁体   English

我不能在 C 中操作位域

[英]I can't manipulate bit fields in C

I wanted to implement LFSR(linear feedback shift registers) in C to generate random bits.我想在 C 中实现 LFSR(线性反馈移位寄存器)以生成随机位。 When I try to modify an individual bit or just assign a short value to memory block, all the bits set to 1. How can I stop this from happening?当我尝试修改单个位或只是为内存块分配一个短值时,所有位都设置为 1。我怎样才能阻止这种情况发生?

struct lfsr{
    //... 
    union{
        unsigned short ff_0 : 1;
        unsigned short ff_1 : 1;
        //... 
        unsigned short ff_f : 1;
        unsigned short ff;
    }flip_flops;
};

int main() {
    struct lfsr gen;
    gen.flip_flops.ff = 1;      //all the ff's set to 1
    gen.flip_flops.ff = htons(0x0001);//all the ff's set to 1
    gen.flip_flops.f_0 = 1;     //all the ff's set to 1
    gen.flip_flops.f_0 = 0;     //all the ff's set to 0
}

The problem is that the union means that each and every one of the one-bit bitfield members access the exact same one bit.问题是联合意味着每一位位域成员访问完全相同的一位。 What you want to do is你想做的是

union lfsr{
    //... 
    struct {
        unsigned short ff_0 : 1;
        unsigned short ff_1 : 1;
        //... 
        unsigned short ff_f : 1;
    }flip_flops;

    unsigned short ff;
};

You are probably understanding the union differently.您可能对工会有不同的理解。 All the bit-fields are aliased at the same location.所有位域都在同一位置别名。 You probably want to do something like this:你可能想做这样的事情:

struct lfsr{
  //... 
  union{
    struct {
      unsigned short ff_0 : 1;
      unsigned short ff_1 : 1;
      //... 
      unsigned short ff_f : 1;
    };
    unsigned short ff;
  }flip_flops;
};

You can have a look here about differences between a struct and a union.您可以在此处查看结构体和联合体之间的差异。

Update:更新:
As per the comments @the-busybee regarding the alignment of bit-fields based on architecture is also worth noting regarding portability of the code across various architectures.根据@the-busybee 关于基于架构的位字段对齐的评论,关于代码在各种架构之间的可移植性也值得注意。
Refer answers here regarding the discussion on bit endianess.有关位字节序的讨论,请参阅此处的答案。

When you declare an Union, all elements of Unions are part of same memory.当您声明一个 Union 时,Union 的所有元素都是同一内存的一部分。 They are just accessed differently.它们只是以不同的方式访问。

 union{
        unsigned short ff_0 : 1;
        unsigned short ff_1 : 1;
        //... 
        unsigned short ff_f : 1;
        unsigned short ff;
    }flip_flops;

Here, ff_0 and ff_1 are same memory and so is ff That is why, when you assign a value to ff_0, it automatically assigned to ff_1.在这里, ff_0ff_1是相同的内存, ff也是如此。这就是为什么当您为 ff_0 赋值时,它会自动分配给 ff_1。 So what you are observing is correct.所以你的观察是对的。

What you should do is, create a structure with 15 bit fields.您应该做的是,创建一个具有 15 位字段的结构。 Then union should be struct and unsigned short.那么 union 应该是 struct 和 unsigned short。

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

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