Hex to ascii

Hi,
does anybody know a way to convert hext to ascii in a template?

This used to work:

{% if states('sensor.line_state').strip('\x00') == 'SHOWTIME' %}

After some update (don’t know which) I have to work with the hex value:

{% if states('sensor.line_state').strip('\x00') == '0x53484f5754494d45000000000000000000' %}

Any ideas?

Thank you guys!!!

You’ll have to convert it and there’s no easy way in jinja. Using this template, you can get what you want:

{%- set line = states('sensor.line_state').replace('0x','') %}
{%- set chars = "abcdefghijklmnopqrstuvwxyz" %}
{%- set n = 2 %}
{%- set ns = namespace(value='') %}
{%- for i in range(0, line | length, n) %}
{%- set c = chars[line[i:i+n] | int('', 16) - 65] %}
{%- if c is defined %}
{%- set ns.value = ns.value ~ c | upper %}
{%- endif %}
{%- endfor %}
{%- if ns.value == 'SHOWTIME' %}
...
2 Likes

@petro you didn’t exaggerate :dizzy_face:
Thank you!!!

@petro Thanks - that’s great :clap: how can i use this (with a nextion display) with multines. I imagin, i set a varialbe (like text_line01 , text_line02 and text_line03) in the nextion userinterface. But how will it automatic split a source varible to this trhree variable (after 20 letter).
Sorry, i’m not a pro :see_no_evil:
Thanks a lot

For anyone that needs more than just uppercase letters, please adjust the chars and the offset (65 in petro’s example changes to 32)

          {%- set line = value_json.Artist.replace('0x','') %}
          {%- set chars = " !'#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" %}
          {%- set n = 2 %}
          {%- set ns = namespace(value='') %}
          {%- for i in range(0, line | length, n) %}
          {%- set c = chars[line[i:i+n] | int('', 16) - 32 ] %}
          {%- if c is defined %}
          {%- set ns.value = ns.value ~ c %}
          {%- endif %}
          {%- endfor %}
          {{ ns.value }}

This code isn’t really needed anymore now that regex exists

Would it be possible to share how to do that with regexes?

I probably jumped the gun with that comment because the incoming string for OP is so unique. Here’s it using regex

{% set input = value_json.Artist %}
{% set input = (input | regex_findall('.{1,2}') | list)[1:] | map('int', base=16) | map('pack', '>I') | map('string') | map('replace', "\\x00", "") | map('regex_findall', "b'([a-zA-Z]{1})'") | map('first') | select('defined') | join %}
{{ input }}