views:

76

answers:

2

I want to send a a Uint16 over the network. I've had a look at the different .NET serializers available. According to this http://stackoverflow.com/questions/1884755/f-serialize-discriminated-union-why-so-many-bytes using a BinaryFormatter will generate overhead bytes that represent meta-data for that type. A result of this would be that UInt16, once passed through that formatter, may not be represented as 16 bits. I need a way to convert that UInt16 such that I get 16 bits from it that I can send to the program at the other end of the socket.

+2  A: 

I think you can use System.BitConverter class:

static member GetBytes : 
        value:uint16 -> byte[] 

http://msdn.microsoft.com/en-us/library/8wwsdz3k.aspx

Stringer Bell
Also beware of endianness of the host. Let's say it runs Mono on a PowerPC chip or Compact Framework for Xbox 360... You may want to take care of that. Novell rolled out their own converter: http://www.mono-project.com/Mono_DataConvert
Stringer Bell
A: 

I just found the BitConverter class and it looks like it does what I want:

byte_array = BitConverter.GetBytes header.id

where header.id is UInt16

sashang
Yup, that's what I was saying!
Stringer Bell
Yeah - didn't see your post when I answered my question. At least we agree.
sashang