1

I have a List that I'm adding 3 bytes to one of which is the length of a string that I'm dynamically passing to my method. How can I determine the length of that string and convert the int into a value that would be accepted in my list.add() method.

Code below:

string myString = "This is a sample string...I need its length";
int theLength = myString.Length;
List<byte> lb = new List<byte>();
lb.Add(0x81);
lb.Add(theLength); // this doesn't work
lb.Add(0x04);

TIA

1
  • 1
    Does the string length need to be stored in 1 single byte? Commented Feb 1, 2012 at 16:31

3 Answers 3

2

Try this:

lb.AddRange(BitConverter.GetBytes(theLength))

Of course, you may decide you only need the least significant bit, in which case you could do a simple cast, or index into the result of GetBytes(), which will be 4 bytes long in this case.

More on BitConverter: http://msdn.microsoft.com/en-us/library/system.bitconverter.getbytes.aspx

Sign up to request clarification or add additional context in comments.

Comments

1

Provided the string's length is within the byte range:

lb.Add((byte)theLength);

2 Comments

doh! not sure why I didn't think of trying this. Thanks. What would be maximum length of the string to fall in the byte range? <-- newb with bit/byte stuff sorry.
@ChristopherJohnson 255 characters at max but if you don't want to get into trouble, you should implement redneckjedi's suggestion which will work regardless of the size of the string. Be aware though that in this case the string's length will span multiple bytes.
1

You have to cast your length into a byte:

lb.Add((byte)theLength);

But as you might guess, your length won't always fit into a single byte. Be more specific about what you expect to do with your list of bytes, we might could provide a better answer (such as using BinaryReader/BinaryWriter instead of a list of bytes).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.