Get a float from 4 bytes through UDP Network library

Status
Not open for further replies.

redrocks

Member
Licensed User
Longtime User
Hi,
I am receiving data on UDP_PacketArrived Event from an external device, the data is a float number originally occupying 4 bytes on Packet.Data buffer, on C++ the way to get the float number from the buffer is to do an Union like: unsigned char byt[4]; float number; but I don't have Unions or pointers in Basic4Android so I don't know how to get the original float from the UDP byte buffer in a simple way. Can someone give me a clue to make it work? Thanks
 
Last edited:

redrocks

Member
Licensed User
Longtime User
Hi,

I have found the solution so I answer to myself:
Sub UDP_PacketArrived(Packet as UDPPacket)
Dim raf as RandomAccessFile
Dim value as Float
raf.Initialize3(Packet.Data,True) ' Pass the byte buffer to raf
value=raf.ReadFloat(raf.CurrentPosition) ' save the float from buffer
raf.close 'Now the transmitted float is in variable "value"
End Sub
:)
 
Upvote 0

PierPaduan

Active Member
Licensed User
Longtime User
Hi.
Using redrocks solution, I have modified it for my specific purposes.
Under here the two subs to convert:
Thanks a Lot redrocks.

- Four bytes of an array in a float number: FourBytesToFloat

- One float number in four bytes in an array: FloatToFourBytes

********************************
Sub FourBytesToFloat(buffer() As Byte) As Float
' Thanks a Lot to "redrocks" member of basic4android forum.
Dim raf As RandomAccessFile
Dim value As Float
raf.Initialize3(buffer,True) ' Pass the byte buffer to raf
value=raf.ReadFloat(raf.CurrentPosition) ' save the float from buffer
raf.close 'Now the transmitted float is in variable "value"
Return value
End Sub
********************************
Sub FloatToFourBytes(value As Float) As Byte()
Dim raf1 As RandomAccessFile
Dim buffer(4) As Byte
raf1.Initialize3(buffer,True) ' Pass the byte buffer to raf
raf1.WriteFloat(value,raf1.CurrentPosition) ' save the float in the 4 bytes buffer
raf1.close
Return buffer
End Sub
********************************
 
Upvote 0
Status
Not open for further replies.
Top