Converting an Integer value to Binary Flags

(not sure if that's the correct term, so let me know if it's not!)

I was working with some android code (that I did not write) and came across a configuration variable that was set with a very large integer value. This config accepts a lot of different flags while also accepting a sum of any combination of said flags, all values being potencies of 2.

Ex:

  • 1 = 2^0 = flag A
  • 2 = 2^1 = flag B
  • 4 = 2^2 = flag C
  • 8 = 2^3 = flag D
  • 16 = 2^4 = flag E

So you can set the variable to 1 (A), 2 (B), 3 (1+2, A and B), all the way to (in this case) 31 (1+2+4+8+16 = A, B, C, D and E).

When we have such few options, it's easy to mentally get a value like 20 and break it down to its parts (4+16 = C and E).

This code, on the other hand... had variables set to numbers like 10737411. Yeah, good luck breaking that down without any help (and if you do can break it down, kudos to you!)

To fix the problem, I needed to see which flags were involved, which meant breaking it down.

Not knowing the term for this type of conversion (and knowing that what to search is a HUGE part of fixing problems), I couldn't find an online tool/script to help me out... so I did what developers do best: created my own solution. The solution is in javascript because it's my go-to (and favorite) language, haha.

jsfiddle.net/fiote/eukz6fs5/12

While 90% of that fiddle is UI stuff (html, css and javascript do display the result) this is important part:

carbon.png

This solved the problem just fine, but I noticed I was calculating the potency twice... and decided to, just for fun, try to shrink this code. The result was:

carbon (1).png

Which is amazing, but it's also something I really do NOT like. I usually write my codes to be clean and without shortage of lines, but it was fun nonetheless!

And if you were curious, the values/flags that sum up to 10737411 are: 1, 2, 256, 512, 1024, 4096, 16384, 32768, 65536, 131072, 2097152 and 8388608. Phew!