'How can I find the big endian key in a message?

I am trying to read a binary message from an ESP32 using a broker; i wrote a phyton script where I subscribe the topic. the message that i actually receive is:

b'\x00\x00\x00?'

this is a float binary little endian message but I don't the key to decode it. Is there a way to find the decode key based on this data? This is my python code:

    import paho.mqtt.client as mqtt


def on_connect1(client1,  userdata1, flags1, rc1):
    
    client1.subscribe("ESP32DevKit123/mytopic")

def on_message1(client1, userdata1, msg1):
    print(msg1.topic+" "+ "TESTENZA: "+str(msg1.payload))

client1 = mqtt.Client()

client1.username_pw_set(username="myuser",password="mypassword")

client1.on_connect = on_connect1

client1.on_message = on_message1

client1.connect("linkclient", portnumber, 60)


def twosComplement_hex(hexval):
    bits = 16 # Number of bits in a hexadecimal number format
    on_message1 = int(hexval, bits)
    if on_message1 & (1 << (bits-1)):
    on_message1 -= 1 << bits
    return on_message1


client1.loop_forever()

It also gives me an error in the line on_message1 -= 1 << bits; the error says: Expected intended block pylance. Any solutions?



Solution 1:[1]

The data you provided is b'\x00\x00\x00?' - I'm going to assume that this is 0000003f (please output hex with msg1.payload.hex()).

I'll also assume that by "float binary little endian" you mean a big endian floating point (IEE754) - note that this does not match up with the algorithm you are using (twos compliment). Plugging this input into an online tool indicates that the expected result ("Float - Big Endian (ABCD)") is 8.82818e-44 (it's worth checking with this tool; sometimes the encoding may not be what you think it is!).

Lets unpack this using python (see the struct docs for more information):

>>> from struct import unpack
>>> unpack('>f', b'\x00\x00\x00\x3f')[0]
8.828180325246348e-44

Notes:

  • The [0] is there because unpack returns an array (you can unpack more than one item from the input)
  • >f - the > means big-endian and the f float (standard size = 4 bytes)

The reason your original code gives the error "Expected intended block" is due to the lack of indentation in the line on_message1 -= 1 << bits (as it follows an if it needs to be indented). The algorithm does not appear relevant to your task (but there may be details I'm missing).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1