Get float as int without changing value

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Boapuosduhgjpqpv

How to change type of variable from float to int without changing variable’s value?
For example in C it’s possible with ```
float a = 7.5F;
int b = *(int *)&a;

I want to send float from Godot to my C server. On server I convert float to host byte order like uint32 (only swap 4 bytes), and I get values, very different from client, but all is fine with `u*` (`u8`, `u16`, `u32`, `u64`) types
:bust_in_silhouette: Reply From: jgodfrey

Is this what you’re after?

var f = 7.5
var i = int(f)

… prints 7

No, I want to change ONLY type (copy bytes from float f to int i). Code on C prints 1089470464. How to do same on Godot?

Boapuosduhgjpqpv | 2023-04-01 05:18

this how you casting in gdscript.
my previous script was in C#.
GDScript will look like this

var a = 10.5
var b :int
b = float(a)

[Ignore]Line 5 (NARROWING_CONVERSION):Narrowing conversion (float is converted to int and loses precision).

a is not changed, b is 10; you can ignore warning

Moreus | 2023-04-01 06:32

I need to fully copy content of a to b, bit by bit. I don’t need to cast float to int. Result should be, like in C, 1089470464, nor 7, nor 10 (in second example)

Boapuosduhgjpqpv | 2023-04-01 13:54

in Godot C#:

    float a = 7.5f;
    int b = BitConverter.SingleToInt32Bits(a);



Moreus | 2023-04-01 17:55

:bust_in_silhouette: Reply From: Moreus

By casting

float a = 10.5f;
int b;
b = (int)a;

I want to send float as int in Godot (like in your code) and receive in C as int, then do something like *(float *)&a; (how to do Godot part?).
Or I can send float in Godot by PackedByteArray.encode_float()and change endianness of float, sent by Godot (don’t know how too).

Boapuosduhgjpqpv | 2023-04-01 05:28

:bust_in_silhouette: Reply From: Boapuosduhgjpqpv

Godot part was perfect, I problem was with server. Float appends in Godot to PackedByteArray like uint32, like I expected.