Question Authors' Forum

How to display the binary form of digital template parameters in the question text?

by Hongchuan Liu -
Number of replies: 2
How to display the binary form of digital template parameters in the question text?

Re: How to display the binary form of digital template parameters in the question text?

by Richard Lobb -

I assume you have a randomly generated integer that you wish to display in binary? In which case I think you'll have to write Twig to convert it to a binary string. Something like the following (which I would suggest you put in the template parameters rather than in the question), which you can play with here on Twig fiddle.

{% set ndecimal = random(0,65535) %}
{% set n = ndecimal %}
{% set binary = "" %}
{% set power = 32768 %}
{% for i in range(0, 15) %}
{%    if n >= power %}
{%        set binary = binary ~ "1" %}
{%        set n = n - power %}
{%     else %}
{%        set binary = binary ~ "0" %}
{%     endif %}
{%     set power = power // 2 %}
{% endfor %}

Decimal {{ ndecimal }} is {{ binary }} in binary.

Re: How to display the binary form of digital template parameters in the question text?

by Hongchuan Liu -
{% set ndecimal = random(15, 20) %}{% set n = ndecimal %}{% set binary = "" %}{% for i in range(0, 15) %}{%    if n >0 %}{%        set binary = (n % 2) ~ binary %}{%        set n = n // 2 %}{%     endif %}{% endfor %}{ "num":"{{ ndecimal }}","bin":"{{binary}}"}

I put the above  in the template parameters and it works well.

Thanks a lot.