Assigning Data to byte[]

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm looking to populate a byte array of some fixed size to send out over
a UDP connection. The data in the byte array is mixed between characters
and binary.

I'm a beginner to this language.

I can assign the character data by the byte. However, I'm not sure how I
would
assign a binary value to a certain location in a byte array where the value is
greater than 255. I have an unsigned short and want to assign it to a
specific
location in the byte array.

What is the best way to do this?

thanks!
 
TRW1313,
I would consider using either a System.IO.BinaryWriter or the methods on
System.BitConverter along with Array.Copy or Buffer.BlockCopy.

Hope this helps
Jay
 
given "private data[] as byte;"

....
data[158] = value;
....
would set the 159th ([0] is the 1st) element of the array to the value of
the variable "value".

Look also at the Convert.ToXXX() functions (in the Convert class) to convert
many things from/to a byte or byte array.
 
Thanks Jay for the help. I will look those over.

I thought the BitConverter would get the data out of the byte array for me but
not put it. I will recheck.

thanks again!
 
TRW,
BitConverter can go both ways.

For example BitConverter.ToUInt16 will take the array & convert it to an
unsigned short.

While BitConverter.GetBytes(System.UInt16) will take an unsigned short &
convert it to a byte array.

Hence I would use BitConverter.GetBytes to convert the unsigned short to a
byte array, then use Array.Copy or Buffer.BlockCopy to "put" this byte array
into the larger byte array.

I normally prefer BinaryWriter (possibly over a MemoryStream) as it
encapsulates the above nicely.

Hope this helps
Jay
 

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

Back
Top