 # How to convert a number to binary?

This is just for fun!

What’s your best formula for converting a number to a binary representation?

E.g. if you are given 24, you should output a list like 0,1,1,0,0,0.

Leading zeros are ok. Can be big or little endian (meaning, the 1 place can be on the right or left).

Looking forward to seeing what you can come up with. I struggled quite a bit with this, it was fun You can see mine doesn’t handle 0s as input very well 1 Like

Hi @cnr
first of all, I officially hate you! I had a lot of work to do today and you infected me with this trick.

I came up with this solution:

Basically the formula is:

``````If(Number = 0,0,
Sequence(Log(Number, Base).RoundDown(), 0, -1)
.FormulaMap(CurrentValue.WithName(step,
RoundDown(Number / Power(Base, step)).Remainder(Base)
)
).Join("")
)
``````

Now I’m curious about yours (and others’)! Edit:
Slightly changed for multi-base conversions

And multi-symbol…

Ok, now I really stop.

1 Like Woooooow! That’s so cool! I didn’t even think to make it multi-base. I figured it would be much more complicated, but it’s basically the same as the original algorithm.

Well done! The use of `Sequence(start, 0, -1)` is very clever! Nice work Here’s mine for binary only:

``````Sequence(0, Ceiling(Log([expected outcome], 2))).ReverseList().FormulaMap(
If(IsOdd(Floor([expected outcome] / Power(2, CurrentValue))),
1,
0
)
)
``````

Yeah: it’s basically the same.
I was very curious because without recurring functions is always quite tricky.

`Remainder()` instead of `IsOdd()` acts as the multi-base enabler, this is the only substantial difference.

Let’s see what come if somebody else is compulsive enough to spend some time on it 2 Likes

Yeah I was also confused how to do it at first without recursive functions. All my base changing algorithms have been recursive. Fun (and surprisingly easy) to do it as a loop.

Another way to do just the binary: convert to hex using existing formula, then take each hex number and convert it into 4 bits e.g. like this:

``````ToHexadecimal(312).Split("").FormulaMap(
Concatenate(
If(Find(CurrentValue, "89ABCDEF") != -1, "1", "0"),
If(Find(CurrentValue, "4567CDEF") != -1, "1", "0"),
If(Find(CurrentValue, "2367ABEF") != -1, "1", "0"),
If(Find(CurrentValue, "13579BDF") != -1, "1", "0")
)
).Concatenate()
``````

Another version, less hardcoding:

``````ToHexadecimal(312).Split("").FormulaMap(
CurrentValue.ToNumber(16).WithName(Hex,
List(8, 4, 2, 1).FormulaMap(
RoundDown(Hex / CurrentValue).Remainder(2)
)
)
).ListCombine().Concatenate()
``````

Once you get out of decimal, it’s easy to do oct <–> bin <–> hex.
My assumption is that ToHexadecimal would be much more performant (a native integer loop or whatever) than calculating powers and dividing by those

1 Like