In today’s Dublin Code Kata, we revisited a bit of classic Comp Sci - integer vs binary representation of numbers! And I learned that converting integers to binary numbers isn’t all that hard in Javascript :)

Binary Code

For example, to convert the integer 4 to the binary number 100 you use…

(4 >> 0).toString(2) # gives "100"

And if you want to do chopping of right most digits change the 0 to the number of digits you want to chop off…

(4 >> 1).toString(2) // gives "10"
(4 >> 2).toString(2) // gives "1"

Or if you want to append zeros, use the opposite…

(4 << 0).toString(2) // still gives "100"
(4 << 1).toString(2) // still gives "1000"
(4 << 2).toString(2) // still gives "10000"

These are called right shift (») and left shift operators («) and there is a variation on the right shift called a zero-fill right shift (»>), as opposed to a sign-propagating right shift (good old »). The difference becomes interesting when you deal with numbers that don’t fit into a 32 bit integer (the upper bound being the magical 2147483647 ).

So if we take a cool two and a half billion we see

(2500000000 >> 0).toString(2) // gives "-1101010111111010000011100000000"
(2500000000 >>> 0).toString(2) // gives "10010101000000101111100100000000"

And that all stemmed from today’s enjoyable challenge A Diversion. Thanks to Prag Dave for sharing! And thanks to Miles McGuire for bringing the bitshift brains and explaining the more esoteric cases!

Here’s some more on bitwise operators and more on bitwise operators in Javascript.