我想用C语言实现LFSR(线性反馈移位寄存器)以生成随机比特。但是当我尝试修改单个比特或将短值分配给内存块时,所有的比特都会被设置为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
}
union
来处理位域?我会使用struct
。 - prog-fhuint16_t
)上的位运算符,而不是位域,如果您不希望在更改编译器或平台时出现任何意外情况! - th33lf