helion3
helion3

Reputation: 37381

Calculating bytes needed to store a string using BinaryWriter

I'm using BinaryWriter to write a string to a file. For unrelated reasons I need to calculate how many bytes this will require but I'm seeing results that don't match the documentation.

With this test code:

using (var stream = new FileStream(filePath, FileMode.Create)) {
    using (var writer = new BinaryWriter(stream)) {
        writer.Write("Test");
    }
}

I expect the file to be 8 bytes:

However, the written file is only 5 bytes, and all of my file offset math works when I assume strings are always Encoding.UTF8.GetByteCount(str) + 1 bytes.

I'm not clear on where the difference is.

This is being tested in Unity 5.6, which uses Mono / .NET 2.0 and some Mono / .NET 3.5.

Upvotes: 2

Views: 377

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

I'm surprised that documentation says it writes size uncompressed. It is very wasteful and I expect compressed format for length provided by BinaryWriter.Write7BitEncodedInt which indeed requires 1 byte for integer below 127.

Reference code confirms that expectation:

 public unsafe virtual void Write(String value) 
 {
     ... 
     int len = _encoding.GetByteCount(value);
     Write7BitEncodedInt(len);

Upvotes: 1

Related Questions