I’ve a fallowing code which receives byte and probably has to perform convert to float and represent its converted values :
public float DecodeFloat(byte[] data)
{
float x = data[3]|data[2]<<8|data[1]<<16|data[0]<<24;
return x;
}
// receive thread
private void ReceiveData()
{
int count=0;
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("10.0.2.213"), port);
client = new UdpClient(remoteIP);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
Vector3 vec,rot;
float x= DecodeFloat (data);
float y= DecodeFloat (data + 4);
float z= DecodeFloat (data + 8);
float alpha= DecodeFloat (data + 12);
float theta= DecodeFloat (data +16);
float phi= DecodeFloat (data+20);
vec.Set(x,y,z);
rot.Set (alpha,theta,phi);
print(">> " + x.ToString() + ", "+ y.ToString() + ", "+ z.ToString() + ", "
+ alpha.ToString() + ", "+ theta.ToString() + ", "+ phi.ToString());
// latest UDPpacket
lastReceivedUDPPacket=x.ToString()+" Packet#: "+count.ToString();
count = count+1;
}
Is there anyone to put me in the right way, please?
Given 4 bytes, you would normally only “shift” (
<<) if it is integer data. The code in the question basically reads the data as anint(via “shift”), then casts theintto afloat. Which is almost certainly not what was intended.Since you want to interpret it as
float, you should probably use:where offset is the 0, 4, 8, 12 etc shown in your
data + 4,data + 8, etc. This treats the 4 bytes (relative tooffset) as raw IEEE 754 floating point data. For example:Note that this makes assumptions about “endianness” – see
BitConverter.IsLittleEndian.Edit: from comments, it sounds like the data is other-endian; try:
If you need to optimize this massively, there are also things you can do with unsafe code to build an
intfrom shifting (picking the endianness when shifting), then do an unsafe coerce to get theintas afloat; for example (noting that I haven’t checked endianness here – it might misbehave on a big-endian machine, but most people don’t have those):Or crazier, and CPU-safer: