Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | programagor |
My code currently calculates the single-precision float manually based on the IEEE 754 specs. However, in languages like C, this entire casting operation is effectively a nop
. Is there a better (faster) way to do this conversion?
func bin2float(pkt:PoolByteArray) -> float:
#Convert packet to an array of bools
var arr:Array=[]
for byte in pkt:
for _i in range(0,8):
arr.append(byte%2)
byte/=2
#Extract sign
var r_sign:int
if arr[31]==1:
r_sign=-1
else:
r_sign=1
#Extract exponent
var r_exp:int=0
for i in range(30,22,-1):
r_exp*=2
r_exp+=arr[i]
r_exp-=127
#Extract mantissa
var r_mant:float=0
for i in range(0,23):
r_mant+=arr[i]
r_mant/=2
r_mant+=1
return r_sign*pow(2,r_exp)*r_mant
I tried using some of the Data Packet classes, but they seem to require an entire protocol setup to use.