Marshal single/float types

  • Thread starter nojo(k)e via DotNetMonster.com
  • Start date
N

nojo(k)e via DotNetMonster.com

Hi all,

I have to deal a lot with serial data exchange between a .NET (1.1)
application running on a PC on one side and controler based devices
programmed in plain C on the other. The latter expect data as a stream of
bytes, extracting numerical values or char[] by 'counting and casting'
(e.g. int n = *(int*)&data[0], byte b = *(byte*)&data[4]) (Very old
fashioned, but still real)

For 'simple' types like char[] or the various int types I use Marshal.Read /
Write....() methods to write the values into and back out of a byte[]
exchanged between the machines, but I didn't find a way to to access the
mere 4 bytes representing the value of a System.Single (==float) struct.

I stumbled over the Marshal.Copy() method, but this expects an 'unmanaged
destination', whereas byte[] is managed and therefore not accepted.

Maybe there is a more simple approach I can't see?

Thanks for any help,

nojo
 
B

Ben Voigt

Something like this?

public static FloatType Encode(float f)

{

return BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);

}

public static float Decode(FloatType enc)

{

return BitConverter.ToSingle(BitConverter.GetBytes(enc), 0);

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top