bit-fields

Integer to bitfield as a list

旧时模样 提交于 2021-02-06 15:21:26
问题 I've created a method to convert an int to a bitfield (in a list) and it works, but I'm sure there is more elegant solution- I've just been staring at it for to long. I'm curious, how would you convert a int to a bitfield represented in a list ? def get(self): results = [] results.append(1 if (self.bits & 1) else 0) results.append(1 if (self.bits & 2) else 0) results.append(1 if (self.bits & 4) else 0) results.append(1 if (self.bits & 8) else 0) results.append(1 if (self.bits & 16) else 0)

Reset all bits in a c bitfield

浪子不回头ぞ 提交于 2021-01-28 04:00:18
问题 I thought that using a C bitfield instead of a int along with a bunch of #define s would give a better-to-read code and reduce the need for adapting existing code when adding new fields. Is there any possibility to reset all Bits in a C bitfield to zero with a single command as the int - #define -method provides? Examples: #define MYFLAG_1 0x01 #define MYFLAG_2 0x02 #define MYFLAG_3 0x04 int myflags = MYFLAG_1 | MYFLAG_3; /* Reset: */ myflags = 0; versus struct { int flag_1 : 1; int flag_2 :

Reset all bits in a c bitfield

▼魔方 西西 提交于 2021-01-28 03:44:19
问题 I thought that using a C bitfield instead of a int along with a bunch of #define s would give a better-to-read code and reduce the need for adapting existing code when adding new fields. Is there any possibility to reset all Bits in a C bitfield to zero with a single command as the int - #define -method provides? Examples: #define MYFLAG_1 0x01 #define MYFLAG_2 0x02 #define MYFLAG_3 0x04 int myflags = MYFLAG_1 | MYFLAG_3; /* Reset: */ myflags = 0; versus struct { int flag_1 : 1; int flag_2 :

Overflow in bit fields

て烟熏妆下的殇ゞ 提交于 2020-12-29 05:24:13
问题 can I trust that the C compiler does modulo 2^n each time I access a bit field? Or is there any compiler/optimisation where a code like the one below would not print out Overflow? struct { uint8_t foo:2; } G; G.foo = 3; G.foo++; if(G.foo == 0) { printf("Overflow\n"); } Thanks in Advance, Florian 回答1: Yes, you can trust the C compiler to do the right thing here, as long as the bit field is declared with an unsigned type, which you have with uint8_t . From the C99 standard §6.2.6.1/3: Values

How to use bitfields that make up a sorting key without falling into UB?

坚强是说给别人听的谎言 提交于 2020-12-13 04:55:26
问题 Let's say I want to have the following bitfield: struct SortingKey { uint8_t a: 2; uint8_t b: 4; uint8_t c: 2; } To use a simple integer comparison, I may need to wrap it into an union like this and use value for sorting: union UnionSortKey { SortingKey key; uint8_t value; } However, in C++, reading an inactive union member is Undefined Behaviour. How can I guarantee that I do not fall into UB but keeping a simple integer comparison? 回答1: You can't use union for type punning, In C++20, you