Converting Hex to Int from power meter for -ve values

I am trying to convert a power meter reading from hex to decimal using signed 2 compliment as per here - Hexadecimal to Decimal Converter (rapidtables.com)

For example:

000001A1 = 417
FFFFFCAF = -849

Now I am using this template for the conversion:

value_template: “{{ 000001A1 | int(base=16) }}”

This works fine for the the first example as it converts to 417

However for the second i.e.

value_template: “{{ FFFFFCAF | int(base=16) }}”

It converts to 4294966447 instead of -849.

What is the templating code I need to properly return decimal from signed 2’s complement?

Tried to google out but really stuck - any help appreciated.

BTW its negative because of solar export to the grid.

Thanks

1 Like

Following… I have the exact same scenario. Template to bring data out of MQTT… 2’s complement binary represented as hex… MSB is not considered negative, so get massive results.

This I have resolved this: for me - I had to update the template to manually do the complement…

Specifically for the Hildbrand MQTT input I used:

- platform: mqtt

    name: "Grid Instant Electricity"

    state_topic: "SMART/HILD/BCDDC2C22DA4"

    unit_of_measurement: 'W'

    value_template: "{% set value = value_json['elecMtr']['0702']['04']['00']|int(base=16) %}{% if (value > 0x80000000) %}{{ ((0xFFFFFFFF - value) * -1) | int }}{% else %}{{ value | int }}{% endif %}"

    icon: 'mdi:flash'
1 Like