How to Calculate String Length in Bytes?

P

PJ Olson

I have a string that I am writing to a binary file. I am trying to determine
the size of the string in bytes as it will be stored in the file.

Currently, the string is 19 characters in length so I am using the following
calculation to get the right size:

(timestamp.length * 2) - 14

But, the string could be variable size which will mess up my the
calculation. Is there a function that does this?

Thanks,
PJ
 
I

Ivar

First convert string to byte[] and then byte.length.

For more info see System.Text.Encoding - this provides methods to convert
string to bytes.
 
J

Jon Skeet [C# MVP]

Ivar said:
First convert string to byte[] and then byte.length.

For more info see System.Text.Encoding - this provides methods to convert
string to bytes.

You don't need to actually convert it first - you can use
Encoding.GetByteCount.
 

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

Top