Home > Net >  Python float and integer values to bytearray
Python float and integer values to bytearray

Time:07-02

I am working on sending data to another program via serial communication.

This reciever program accepts 78 bytes arrays and for the receiver to understand, each data must be in its own dedicated byte index.

Ex: I have integer altitude value=2500

and the program accepts 4 byte integer value. So I need to fit this integer to theese bytes

I wrote a code like this:


import serial

ser = serial.Serial('COM16', 19200, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE)

size = 78
array1 = bytearray(size)

altitude=2800.0


check_sum = 0

array1[0] = 0xFF
array1[1] = 0xFF
array1[2] = 0x54
array1[3] = 0x52
array1[4] = 15
array1[5] = 27
array1[6] = 0
array1[7] = 0
array1[8] = 0
array1[9] = 0
array1[10] = 0
array1[11] = 0
array1[12] = 0
array1[13] = 0
array1[14] = 0
array1[15] = 0
array1[16] = 0
array1[17] = 0
array1[17] = 0
array1[19] = 0
array1[19] = 0
array1[20] = 0
array1[21] = 0
array1[22] = 0
array1[23] = 0
array1[24] = 0
array1[25] = 0
array1[26] = 0
array1[27] = 0
array1[28] = 0
array1[29] = 0
array1[30] = 0
array1[31] = 0
array1[32] = 0
array1[33] = 0
array1[34] = 0
array1[35] = 0
array1[36] = 0
array1[37] = 0
array1[38] = 0
array1[39] = 0
array1[40] = 0
array1[41] = 0
array1[42] = 0
array1[43] = 0
array1[44] = 0
array1[45] = 0
array1[46] = 0
array1[47] = 0
array1[48] = 0
array1[49] = 0
array1[50] = 0
array1[51] = 0
array1[52] = 0
array1[53] = 0
array1[54] = 0
array1[55] = 0
array1[56] = 0
array1[57] = 0
array1[58] = 0
array1[59] = 0
array1[60] = 0
array1[61] = 0
array1[62] = 0
array1[63] = 0
array1[64] = 0
array1[65] = 0
array1[66] = 0
array1[67] = 0
array1[68] = 0
array1[69] = 0
array1[70] = 0
array1[71] = 0
array1[72] = 0
array1[73] = 0
array1[74] = 1

array1[76] = 0x0D
array1[77] = 0x0A

for x in range(4, 75):
    check_sum  = array1[x]

check_sum % 256

array1[75] = check_sum

ser.write(array1)


Theese first 4 byte and last 2 byte are constant to reciever requirements

My question is

altitude=2800

array1[6] = 0
array1[7] = 0
array1[8] = 0
array1[9] = 0

these 4 bytes are reserved to keep altitude data.

how can i put this altitude data in array with to these byte values

CodePudding user response:

I would go with the struct module. It is specifically designed to address what you are trying to do.

CodePudding user response:

To expand on Niko's answer, this problem can be solved with Python's builtin struct library. However, you don't seem to have specified anything about the required byte order of your application. For example, the following expressions would produce different results:

big_endian = struct.pack(">f", 0.24)
little_endian = struct.pack("<f", 0.24)

print([*big_endian]) # [62, 117, 194, 143]
print([*little_endian]) # [143, 194, 117, 62], the order is reversed

You should check your receiver requirement of endianness and use the appropriate one in your Python script.

  • Related