So your help would be very appreciated.
Code: Select all
import struct
def convert_long_to_bytes(i):
i = i % 4294967296
n4 = i % 256
i = i / 256
n3 = i % 256
i = i / 256
n2 = i % 256
n1 = i / 256
return (n1, n2, n3, n4)
def convert_float_to_MICROCHIP_32bit(x):
print ("x", x)
x_IEEE = struct.pack(">f", x).encode("hex")
print ("x_IEEE", x_IEEE)
bits = bin(int(x_IEEE, 16))[2:].zfill(len(x_IEEE) * 4)
i = 0
val = list(" ")
b_s = bytearray(val)
for char in bits:
current_bit = int(char)
if current_bit == 1:
if (i > 0) and (i < 9):
b_s[i - 1] = "1"
elif i == 0:
b_s[8] = "1"
else:
b_s[i] = "1"
else:
if (i > 0) and (i < 9):
b_s[i - 1] = "0"
elif i == 0:
b_s[8] = "0"
else:
b_s[i] = "0"
i = i + 1
bin_val = str(b_s)
print ("bin_val", bin_val)
hex_val = int(bin_val, 2)
print ("hex_val", hex_val)
bytes_val = convert_long_to_bytes(hex_val)
print ("bytes_val", bytes_val)
return bytes_val
a = 987654321.123456789 #-987654321.123456789 #0.0 #-5.1 #5.1
b = convert_float_to_MICROCHIP_32bit(a)
print b
Regards, Vlado