Bitfield manipulation in C -


The classic problem of testing and setting individual bits in an integer in C is probably one of the most common intermediate-level programming skills in the

You set and test with simple bitmasks like

  unsigned int mask = 1 & lt; & Lt; 11; If (value and mask) {....} test for // bit value. = Mask; Set // bit value & amp; = ~ Mask; // Clean a bit  

There is an argument that this error prone, difficult to maintain, and poor practice. In C language, it provides bit-level access that is typewritten and portable:

  typedef unsigned int boolean_t; #define FALSE 0 # Define TRUE! FALSE typedef union {struct {boolean_t user: 1; Boolean_T zero: 1; Boolean_T force: 1; Int: 28; / * Unused * / boolean_t compat: 1; / * Bits 31 * /}; Int raw; } Flags_t; Int create_object (flags_t flags) {boolean_t is_compat = flags.compat; If (is_compat) flags.force = FALSE; If (flags.force) {[...]} [...]}  

but it makes me cringe

Interesting reasoning for my colleague and I still have unresolved about it are both styles, and I maintain classic bitmask method, easy, safe and clear. My colleague agrees that this is normal and easy, but the bitfield union method is worth some extra lines, to make it portable and secure.

Is there any other logic for both sides? Probably possibly some failure, maybe with endeannisation, that bitmask method can be remembered but where is the structure method safe?

BitFields are not as portable as you think, Do not give any guarantee "()

Do not ignore it, used correctly , either method is safe, both methods allow symbolic access to integral variables is. You can argue that typing method is easy, but it also means more code to review.


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -