How do I convert primitives like int or float to a RawArray (or insert them into an existing one) (2.1.3)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By raymoo
:warning: Old Version Published before Godot 3 was released.

If I want to roll my own network protocol and send packets as in PacketPeer’s put_packet, how would I get primitive types like int into a RawArray?

:bust_in_silhouette: Reply From: raymoo

I left it open just in case but I’m fairly sure now that it isn’t possible to do these kinds of conversions.

In 3.0, it is possible using StreamPeerBuffer and the StreamPeer methods.

It has been ported to 2.1 and will be available in the next release.

raymoo | 2017-08-13 19:47

:bust_in_silhouette: Reply From: mollusca

This seems to work:

var float_in = -0.352141175
#float to RawArray
var float_raw = String(float_in).to_ascii()
#RawArray to float
var float_out = float_raw.get_string_from_ascii().to_float()
	
var int_in = 352141175
#int to RawArray
var int_raw = String(int_in).to_ascii()
#RawArray to int
var int_out = int_raw.get_string_from_ascii().to_int()

On second try it doesn’t work that great for floats, small values get truncated / rounded to zero.

mollusca | 2017-08-07 11:59

I don’t want a textual representation of the number I want:

  • For ints: typical bit vector representation of fixed width integers
  • For floats: IEEE representation of single-precision floating point number

Outputting it as text bloats the size of the data. For example, 50000 in text takes up 5 bytes, as a 32-bit machine representation it is only 4 bytes. It is even worse for floating point, where the text representation can be very long if the entire precision is output as decimal. Something like 1.4534636 (made up number) takes up 9 bytes as opposed to 4 bytes in machine format, bloating it by more than 100%.

raymoo | 2017-08-09 02:41