DEV Community

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

Collapse
 
antoneb profile image
AntoneB

I don't do much programming in Java script and I don't know why one would use bit masks in a language that is mostly for browser side high level coding.

But calling them esoteric and impractical would lead me to believe you don't deal with embedded coding and good old standard c. Often in embedded systems we can't afford to be wasteful with resources, since c has a much smaller compiled foot print than C++ and higher languages it is used.

Also when working with creating a client server protocol that sends and receives data packets (like a multi player game), you often need to send flags that say things like jump, attack, crouch, move, etc..

You could create a struct to send as a packet using a bunch of C++ BOOL's. But here's the rub, if you're using a bool per flag, a bool requires minimum 1 Byte or 8 bits; however, if you use an unsigned int as a bitfield, and bit masks, you can effectively have 8 bools per byte for a char, or uint8_t.

You get 8 times the bool flags, with 1/8th the data packet size. Reducing the data packet size reduces the latency. Also bitwise operators are very fast for the cpu to process.

For Java Script, I'd probably not bother with bitmasks and bitwise operators, but if you are using c or c++ and trying to minimize the amount of memory you're using, bit masks will always beat bool.

Collapse
 
somedood profile image
Basti Ortiz

Yup, you are definitely correct there. Perhaps I have been too harsh on bitmasks. I never really considered embedded systems when I wrote this article. I simply had a "JavaScript mindset", so to speak.