How to determine the number of bytes in a string

  • Thread starter Thread starter Ole
  • Start date Start date
O

Ole

By converting a string in a textbox to a byte array I'll need the byte size
of the string - how to determine that?

Thanks
Ole
 
Encoding.GetByteCount(str) should do the job.

For example, if you chose the UTF8 encoding for the byte representation (the
result depends on the encoding), you can write:

int len = System.Text.Encoding.UTF8.GetByteCount(str);

Bruno
 
Ole said:
By converting a string in a textbox to a byte array I'll need the byte size
of the string - how to determine that?

What method are you using to convert? Every char in the string is two
bytes in size, so if you are just converting the chars directly and not
using any particular encoding, the answer is string.Length * 2.

However, if you are using an encoding, you can either call
Encoding.GetByteCount() or simply call one of the Encoding.GetBytes()
overloads which returns an array of the right length. E.g.:

---8<---
byte[] bytes = Encoding.UTF8.GetBytes("foo");
--->8---

-- Barry
 

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