繁体   English   中英

如何确定 BinaryWriter 写入 memory 需要多少字节?

[英]How to determine how many bytes a BinaryWriter would take to write into memory?

我红色: 一个字符串会占用多少字节? 以及如何知道字符串的大小(以字节为单位)? 和其他一些,但我无法计算出使用 BinaryWriter 通过 MemoryMappedViewStream 通过 MemoryMappedFile 将字符串放入 memory 的确切字节数。

有时取的长度是字符串长度+1,有时是字符串长度+2???

我都试过了:

  • System.Text.ASCIIEncoding.Default.GetByteCount(str)
  • System.Text.ASCIIEncoding.Unicode.GetByteCount(str)

但它们都不起作用。 我尝试了字符串长度加上固定数量,但它也不起作用。

如果我检查 BinaryWriter.BaseStream.Position 之前和之后之间的差异,那么我无法确定一种方法来确定为字符串写入的确切字节数(之后的位置 - position 之前)。 听起来好像有 alignment 或其他我无法弄清楚的东西?

如何每次写入适当数量的字节?

更新

我现在使用Encoding.UTF8.GetByteCount(str) + 1; ,这在大多数情况下给了我几乎正确的尺寸,但并非总是如此。

我根据https://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,08f2e8c389fd32df的 Microsoft BinaryWriter 的源代码找到了我的答案

注意:字符串的长度写在字符串之前,并以 7 位编码,其中大小可能因字符串大小而异(>= 128、>=2^14、> 2^21)。

代码:

    public static int GetBinaryWriterSizeRequired(this string str, Encoding encoding)
    {
        encoding = encoding ?? Encoding.Default;

        int byteCount = encoding.GetByteCount(str);
        int byteCountRequiredToWriteTheSize = 1;

        // EO: This code is based on the Microsoft Source Code of the BinaryWriter at:
        // https://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,2daa1d14ff1877bd
        uint v = (uint)byteCount;   // support negative numbers
        while (v >= 0x80)
        {
            v >>= 7;
            byteCountRequiredToWriteTheSize++;
        }

        return byteCountRequiredToWriteTheSize + byteCount;
    }

来电:

...
_writer = new BinaryWriter(_stream);
_writerEncoding = _writer.GetPrivateFieldValue<Encoding>("_encoding");
...
int sizeRequired = name.GetBinaryWriterSizeRequired(_writerEncoding);

其他(我知道我们不应该调用私有字段,但我做到了):

public static T GetPrivateFieldValue<T>(this object obj, string propName)
{
    if (obj == null)
        throw new ArgumentNullException("obj");

    Type t = obj.GetType();
    FieldInfo fi = null;
    while (fi == null && t != null)
    {
        fi = t.GetField(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        t = t.BaseType;
    }

    if (fi == null)
        throw new ArgumentOutOfRangeException("propName", string.Format("Field {0} was not found in Type {1}", propName, obj.GetType().FullName));

    return (T)fi.GetValue(obj);
}

作为参考,这些都是不好的:

return Encoding.UTF8.GetByteCount(str) + 1;
return System.Text.ASCIIEncoding.Default.GetByteCount(str) + 1; //  sizeof(int); // sizeof int to keep the size
return System.Text.ASCIIEncoding.Unicode.GetByteCount(str) + sizeof(int); // sizeof int to keep the size

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM