Once in a while, when working with Jinja templating engine, you might need to create a random Bit Set with Jinja. Some might also call it a Binary Flag Set.
Basically, this will be a binary number (for example 10110
) where each digit (bit) represents whether something is on/enabled/present or off.
In some systems, this binary number is actually stored as a base 10 integer. So 10110
will be stored as 22
.
Here is how to do it:
{% macro random_binary_flag(len) -%}{% for i in range(0,len) -%}{{ [0,1]|random }}{% endfor %}{%- endmacro -%} {% set CallFlag = random_binary_flag(5)|int(0,2) %}
Now let’s explain it line by line
{% macro random_binary_flag(len) -%}{% for i in range(0,len) -%}{{ [0,1]|random }}{% endfor %}{%- endmacro -%}
A Jinja macro that creates len
number of random bit
{% set CallFlag = random_binary_flag(5)|int(0,2) %}
Here we are just calling the random_binary_flag
macro and asking it to give us a set that consists of 5
bits. Then using the |int(0,2)
operator, we are converting it to a base 10 Integer and assigning the value to the CallFlag
Jinja parameter