本文介绍了将数据写入位域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 大家好! 是否可以在初始化所有 位的位字段中写入值? 示例: struct字段 { unsigned int Bit1:1; unsigned int Bit2:2; } MyFied; 现在,我想将值3写入变量MyField, 使Bit1和Bit2变为TRUE(== 1)。 有什么建议吗? 谢谢!Hi everybody!Is it possible to write a value into a bit field which initializes allbits?example:struct Field{unsigned int Bit1 : 1;unsigned int Bit2 : 2;} MyFied;Now, I would like to write the value 3 to the variable MyField,so that Bit1 and Bit2 become TRUE ( == 1).Any suggestion?Thanks!推荐答案 AFAIK,不是便携式的。 你可以获得的最接近的是具有一个常量结构,其中Bit1 和Bit2设置为1,然后将其分配给相同类型的变量。 例如: struct字段all_bits_one = {1,1}; MyFied = all_bits_one; 如果你不想移动,你可以找出你的实现(或类似的方便对象)如何实现 适当地构建它们并投射到你的结构。 - BR,弗拉基米尔AFAIK, not in a portable way.The closest you can portably get is to have a constant struct with Bit1and Bit2 set to 1, and then assign that to variables of the same type.E.g.:struct Field all_bits_one = { 1, 1};MyFied = all_bits_one;If you don''t want to be portable, you can find out how yourimplementation represents integers (or similar handy objects) and tryconstructing them appropriatelly and casting to your struct.--BR, Vladimir AFAIK,不是以便携的方式。 你可以获得的最接近的是具有Bit1 >和Bit2设置为1,然后将其分配给相同类型的变量。 struct Field all_bits_one = {1,1}; AFAIK, not in a portable way. The closest you can portably get is to have a constant struct with Bit1 and Bit2 set to 1, and then assign that to variables of the same type. E.g.: struct Field all_bits_one = { 1, 1}; 显然: const struct字段all_bits_一个= {1,1}; 如果你想让它保持不变,就像我建议的那样。 MyFied = all_bits_one; 如果你不想要便携,你可以找到你的实现如何表示整数(或类似的方便对象),并尝试适当地构建它们并投射到你的结构。 - BR,VladimirObviously:const struct Field all_bits_one = { 1, 1};if you wanted it constant as I suggested. MyFied = all_bits_one; If you don''t want to be portable, you can find out how your implementation represents integers (or similar handy objects) and try constructing them appropriatelly and casting to your struct. -- BR, Vladimir 这篇关于将数据写入位域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!