本帖最后由 neroxps 于 2020-11-14 14:30 编辑
最近折腾某些小玩意,mqtt过来消息是16进制,格式是固定的两位十六进制。
想取发过来取固定位置的十六进制转成二进制,每位二进制都代表一个二进制传感器。
既然HA展示,那也不想经过其他系统,想在 HA 那边直接转换了。
但是找了一圈没找到咋将16进制转成2进制
上网搜索下16进制转二进制原理,用 jinja2 实现下转换
{% set value = 'CB' %}
{% set high = value[1] %}
{% set low = value[0] %}
{% set high_bin_0 = high | int(high,16)/2/2/2%2 %}
{% set high_bin_1 = high | int(high,16)/2/2%2 %}
{% set high_bin_2 = high | int(high,16)/2%2 %}
{% set high_bin_3 = high | int(high,16)%2 %}
{% set low_bin_0 = low | int(low,16)/2/2/2%2 %}
{% set low_bin_1 = low | int(low,16)/2/2%2 %}
{% set low_bin_2 = low | int(low,16)/2%2 %}
{% set low_bin_3 = low | int(low,16)%2 %}
{{ "%d%d%d%d%d%d%d%d" | format(low_bin_0,low_bin_1,low_bin_2,low_bin_3,high_bin_0,high_bin_1,high_bin_2,high_bin_3) }}
复制代码
上方代码被吐槽效率低下
下方优化版本~
{% set value = 'CBAAA' %}
{% set result = namespace(bin=[]) %}
{% for word in value %}
{% set hex = word | int(word,16) %}
{% set bin_0 = "%d" | format(hex/2/2/2%2) %}
{% set bin_1 = "%d" | format(hex/2/2%2) %}
{% set bin_2 = "%d" | format(hex/2%2) %}
{% set bin_3 = "%d" | format(hex%2) %}
{% set result.bin = result.bin + [bin_0] %}
{% set result.bin = result.bin + [bin_1] %}
{% set result.bin = result.bin + [bin_2] %}
{% set result.bin = result.bin + [bin_3] %}
{% endfor %}
{{ result.bin }}
{{ result.bin[2] }}
复制代码