cool hit counter [Handy] Note the small pitfall of writing string with BinaryWriter - it will prefix string with length-prefixed_Intefrankly

[Handy] Note the small pitfall of writing string with BinaryWriter - it will prefix string with length-prefixed


Previously it was thought that BinaryWriter would write string strictly in the encoding specified at construction (or BOM-free UTF8 if not specified) to the binary of string, as in the following code.

//Set the string"a" write stream, And then get the byte set of the streamdata
using (var ms = new MemoryStream())
{
    using (var bw = new BinaryWriter(ms))
    {
        bw.Write("a");
    }
    byte[] data = ms.ToArray();
}

Because the letter a utf8 encoding is 97, so I expected data only 1 element and the value of 97, but in fact, data has two elements, in order to 1, 97, obviously 97 represents a, but what the hell is the 1 in front, and then try other strings, still in front of 1 or even more bytes, the value is also relatively flaky, in short, is Instead of honestly writing [only] the binary of string, bw adds something that This can be problematic in scenarios where byte correctness is strictly required, such as http request bodies, where the server will be dumbfounded by these extra bytes. So I did some searching and foundMSDNstackoverflow As mentioned early on, the extra bytes in front actually indicate the length of the string, called length-prefixed, which according to a certain SO respondent is for the BinaryReader's ReadString method, which knows the length so it knows where to read it. So if the read side of the stream is not a BinaryReader, these length prefixes are redundant or even harmful, in which case the BinaryWriter.Write(string) method should not be used, and a clean string binary should be written, as follows.

bw.Write(Encoding.UTF8.GetBytes("a"));// Use the right code as needed

Write(byte[]) to write the byte group, but of course it doesn't matter what encoding is specified when constructing bw.

-Bunbi-


Recommended>>
1、Gradlespeed up Saves you a cup of coffee a day
2、Hes a little programming whiz He only4 Half the worlds flags in one lesson
3、360 Super Live Musical Project Settles in Xiangjiang New Area
4、Privacy Defense AI Researchers Release New Algorithm to Fight Facial Recognition
5、What do you think of Japans proposal to allow driverless cars on the road in some areas by 2020

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号