Format characters
I have to program a protocol-communication and there are fields like this (i post the description):
name: length
bytes: 4
comment: the header always contains the length of the telegram. The length is four ASCII digits long ('0'..'9') specifying a ronage of 0000 to 9999.
How can i put this into a buffer with size 20 bytes at the start position 4?
for example the value 20:
buffer[0] ...
buffer[1] ...
buffer[2] ...
buffer[3] ...
buffer[4] = 0
buffer[5] = 0
buffer[6] = 2
buffer[7] = 0
buffer[8] ...
[581 byte] By [
zechasso] at [2007-11-20 11:20:26]

# 1 Re: Format characters
I solved it myself.
If anybode is interested:
_sLen = "0020"
byte _buffer = new byte[20];
Array.Copy(Encoding.ASCII.GetBytes(_sLen.ToCharArray()), 0, _buffer, 0, 4);
This works.
Maybe there's an other solution, but I don't know!
# 2 Re: Format characters
Note that you'll only have 16 bytes free if you create a buffer that's 20 bytes long and put the length into the first four bytes.
Also, are you following a spec for the header? If you're free to choose what it looks like, I'd recommend storing the length as binary numbers rather than decimal numbers, because a binary number allows 256 combinations per byte, while a decimal only allows ten.
Here's a method that could be used to simplify building a packet, and showing how you would use a binary number (a short will suffice in your case.)
public byte[] BuildPacket(string telegram)
{
if (String.IsNullOrEmpty(telegram))
throw new ArgumentException("String 'telegram' was null or empty.", "telegram");
if (telegram.Length > 65535)
throw new ArgumentException("String 'telegram' may not exceed 65535 characters in length.", "telegram");
ushort length = (ushort)telegram.Length;
byte[] buffer = new byte[length + 2];
// The length consists of two bytes, so put the "left-most" part of the
// length into byte #1.
buffer[0] = (byte)(length >> 8);
// Remove the "left-most" part of the length, only putting the "right-most"
// part of it into byte #2.
buffer[1] = (byte)(length & 0xFF);
// Fill the remainder of the buffer with the string data.
Array.Copy(System.Text.Encoding.ASCII.GetBytes(telegram), 0, buffer, 2, telegram.Length);
return buffer;
}