Home All Groups Group Topic Archive Search About

Marshal single/float types

Author
30 Aug 2006 9:24 PM
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


Author
31 Aug 2006 5:20 PM
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);

}



"nojo(k)e via DotNetMonster.com" <u15542@uwe> wrote in message
news:658f4ee04d757@uwe...
Show quote
> 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
>
> --
> Message posted via DotNetMonster.com
> http://www.dotnetmonster.com/Uwe/Forums.aspx/dotnet-new-users/200608/1
>
Author
1 Sep 2006 8:47 AM
nojo(k)e via DotNetMonster.com
Thanks Ben,

thats what I was looking for.

nojo


AddThis Social Bookmark Button