Hi.
I have a number that needs to be converted from decimal to binary. How is it possible to do this?
Let’s say I have the number 4362, how do I convert it to 0001 0001 0000 1010
{{ "{0:b}".format(4362) }}
If you want it padded as you show:
{{ "{:0=16b}".format(4362) }}
and split into fours (probably not the best way):
{{ "{:0=16b}".format(4362)|batch(4)|map('join')|join(' ') }}
These all return strings. You can turn them back to a decimal number using:
{{ "1000100001010"|int(base=2) }}
or if you have spaces:
{{ "0001 0001 0000 1010"|select('in','01')|join|int(base=2) }}
5 Likes
Math wise, Keep dividing by 2 until you can’t and note the remainder each time. The first time you do it the remainder is the least significant bit. Each time you divide is the next bit to the left. Loop division untyyou can’t and the remainders are the binary conversion. Unsure if there’s a function available in a template. Edit @Troon to the rescue
Whats the use case.
Thank you so much