Search code examples
pythonosc

How to decode / encode decimal values in python?


I am using a network protocol to transmit OSC (open sound control messages) back and forth over a network.

The messages are received in a byte array as well as other formats. I am trying to understand the byte array part of it.

An example message, in ascii is

/track_0_volume/x "value" 0.238

The corresponding byte array for that message is

b'/track_0_volume/x\x00\x00\x00,sf\x00value\x00\x00\x00>s\xb6F'

I can see looking at the byte array that there is /track_0_volume/x followed by three null characters, then the ascii values sf, a null character value three more null characters and then >s\xb6F I do not understand what the sf characters are nor how the >s\xb6F at the end represents 0.238

I believe, (I am not that familiar with OSC message formats) that the s indicades that the word value is a string type (as opposed to an int or float) and the next value is a float (i.e. value and .238)

The most confusing part to me is the decimal part at the end: When I try to decode that part of the byte array I get a UnicodeDecodeError: 'utf-8 can't decode byte 0xb6

I have also used struct.unpack('f', b'\b6F') with no success. Anybody know how to decode that?


Solution

  • According to the documentation a floating point number is 32 bits, big-endian.

    >>> struct.unpack('>f', '>s\xb6F')[0]
    0.23800000548362732
    

    Additionally all strings end with a zero byte, plus up to 3 more zero bytes to make the length a multiple of 4. That explains all the \x00 you have; there are 3 strings preceding the float.

    P.S. My example is Python 2.7, yours appears to be Python 3. Adjust accordingly.