0 votes

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.

in Engine by (19 points)

1 Answer

+1 vote
Best answer

Hi,
you can do it with the StreamPeerBuffer

var spb = StreamPeerBuffer.new()
spb.data_array = pkt
var single_float = spb.get_float() 

https://docs.godotengine.org/en/3.0/classes/class_streampeerbuffer.html#class-streampeerbuffer

https://docs.godotengine.org/en/3.0/classes/class_streampeer.html#class-streampeer

by (4,010 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.