Convert received hex-codes to usable negative and positive decimal values

Hi folks,

now i have another problem.

One of my mqqt sensors is a temperature sensor and sends hex values ​​above 0°C starting at #0000
Negative temperatures send values ​​from #ffff down.

When I wrote the whole thing via a PHP script in an SQL database before my integration into the HomeAssistant,
I solved the problem with this code:

      if (hexdec(trim(substr($parts[1],2,5)))/100 > 100){
        $record[$key] = (hexdec('ffff') - hexdec(trim(substr($parts[1],2,5)))) / -100;
      } else {
        $dataset[$key] = hexdec(trim(substr($parts[1],2,5)))/100;
      }

How do I manage to integrate this into the HomeAssistant in exactly the same way?

in a template, something like

{% set val = "#fffd" %}
Input is {{val}}
{% set valdec = int(val[1:], base=16) -%}
Decimal input is {{valdec}}
Adjusted for sign: {% if valdec < 0x7fff %}{{ valdec }}{% else %}{{ valdec - 0x10000 }}{% endif %}
Input is #fffd
Decimal input is 65533
Adjusted for sign: -3

I tried this:

      value_template: > 
        {%set outtempplus = value|replace('#','')|int(base=16,default=0)/100 %}
        {%set outtempminus = value|replace('#','')|(65535 - int(base=16,default=0))/-100 %}
        {{ outtempplus if outtempplus < 100 else outtempminus }}

…but it won’t work

…and I tried this:


      value_template: > 
        {%set outtempdec = int(value[1:],base=16,default=0) %}
        {% if outtempdec > 100 %}{{ outtempdec / 100 }}{% else %}{{ (65535 - outtempdec) / -100 }}{% endif %}

…and I get “NaN”

Please show your full code.

What is the value of value?
Your code is likely wrong but it gives me 655.33 for a value of "#fffd"

mqtt
  sensor
    - name: "Heizung Aussentemperaturfühler"
      unique_id: "heatronic_aussen"
      value_template: > 
        {%set outtempdec = int(value[1:],base=16,default=0) %}
        {% if outtempdec > 100 %}{{ outtempdec / 100 }}{% else %}{{ (65535 - outtempdec) / -100 }}{% endif %}
      unit_of_measurement: "°C"
      state_topic: "home/heizung/aussen"
      state_class: "measurement"

Value is the temperaturemeasurement of my heating.
#0000 is 0,00 °C
#2710 is 100,00 °C
#F82f is -20,00 °C

every hexadecimal digit is 0,01 °C

This works for me

    - name: "Heizung Aussentemperaturfühler"
      unique_id: "heatronic_aussen"
      value_template: > 
        {%set outtempdec = int(value[1:],base=16,default=0) %}
        {% if outtempdec < 0x7fff %}{{ outtempdec / 100 }}{% else %}{{ (outtempdec - 0xffff) / 100 }}{% endif %}
      unit_of_measurement: "°C"
      state_topic: "home/heizung/aussen"
      state_class: "measurement"

image
image

many thanks

why do i have to use hexadecimal valuses für arithmetic operations when i have a decimal value