[.net] Reading strings written by BinaryWriter.Write(string)?

Started by
15 comments, last by HeftiSchlumpf 15 years, 9 months ago
protected void Write7BitEncodedInt(int value){    uint num = (uint) value;    while (num >= 0x80)    {        this.Write((byte) (num | 0x80));        num = num >> 7;    }    this.Write((byte) num);}


Advertisement
You can work this out by writing code that tests all the boundary cases.

FileStream fs = new FileStream("c:\\moo.bin", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs);string moo = "";bw.Write( moo.PadLeft(5, 'X') );bw.Write( moo.PadLeft(127, 'Y') );bw.Write( moo.PadLeft(128, 'Z') );bw.Write( moo.PadLeft(256, 'A') );bw.Write( moo.PadLeft(32767, 'B') );bw.Write( moo.PadLeft(32768, 'C') );fs.Close();


It seems to me, that bit 7 of each byte determines if there is another byte to read. So lengths 0-127 take 1 byte, a length
of 128 requires two bytes, i.e. bit 7 is set to 1 but the real bit 7 is in bit 0 of the next byte, so in this manner 256 seems to be 0x80 0x02

Or I might be talking complete rubbish...

Jans.
And binary reader usesthis courtesy of reflector.

protected internal int Read7BitEncodedInt(){    byte num3;    int num = 0;    int num2 = 0;    do    {        if (num2 == 0x23)        {            throw new FormatException(Environment.GetResourceString("Format_Bad7BitInt32"));        }        num3 = this.ReadByte();        num |= (num3 & 0x7f) << num2;        num2 += 7;    }    while ((num3 & 0x80) != 0);    return num;}

Quote:Original post by Niksan2
And binary reader usesthis courtesy of reflector.
*** Source Snippet Removed ***

And we have a winner! Anyone else find it strange that you have to decompile a system library to determine non-secret, defined behavior?
First off, you do have the ability to add comments and corrections to the MSDN2 pages. This is also documented on the BinaryReader.ReadString page (Yeah, I know...odd place).

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Quote:MSDN Docs
Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.

Lo and behold, it is! I'd probably seen that earlier, but it didn't mean anything to me--especially since I'd just read the Write(string) documentation that said it was either a byte... or a word... or a 4-byte int... or something else.
Quote:Original post by BeanDog
Quote:Original post by Niksan2
And binary reader usesthis courtesy of reflector.
*** Source Snippet Removed ***

And we have a winner! Anyone else find it strange that you have to decompile a system library to determine non-secret, defined behavior?


http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx

btw you can exactly see how its encoded.

This topic is closed to new replies.

Advertisement