DEV Community

Discussion on: Bitmasks: A very esoteric (and impractical) way of managing booleans

Collapse
 
nterreri profile image
Nic Terreri

I think you wrote an explanation of bitfields that is both accessible and in depth, well done.

I think that the best use case for bitfields/bitmasks are found where the various "flags" you toggle on and off are not independent of each other, but have some meaningful relationship, e.g. the values in the field are "additive" in a sense.

For example, log levels are considered additive by some applications: if you log at "info" level, then you also log "error" and "warn" level messages, this relationship between the different possible values is well captured by bitfields by representing the "lowest" value as the smallest value in the field:

enum LogLevel {
  Error = 0b0001,
  Warn = 0b0011,
  Info = 0b0111,
  Debug = 0b1111
}

setLogLevel(LogLevel.Info);

Then whatever is logging can decide whether to log a message or not based on whether the configured log level "has" the specified flag by using bitwise and (&) as you mentioned, or making a numeric comparison:

if (message.level <= this.highestLogLevel) {
  this.doLog(message);
}

Another example is configuring media "directions" (you can run into this with webrtc):

enum MediaDirection {
  Send = 0b01,
  Receive = 0b10,
  All = 0b11
}

In these cases, the values have some meaningful relationship with each other and using bitfields feels quite natural to me to represent these relationships.

Collapse
 
somedood profile image
Basti Ortiz

I never knew that error logs had levels. No wonder they look like hexadecimal gibberish to naive users like me.

WebRTC has a pretty cool API for using bits rather than strings, such as 'forwards', 'backwards', or 'both', to describe media direction. I definitely want to see more of that in modern APIs.