Deep dive into Binary Reader / Writer

time to read 2 min | 257 words

So, as I mentioned, I was doing low level binary IO stuff today, and I started the class going on doing stuff using BitConvertor, FileStream.Write, etc.

After they finished the first exercise, I started to show them how they can replace this tedious code with BinaryReader / BinaryWriter. That was much easier, except that we had strings going into the binary files, and I stopped in the middle to try to read the file written using BinaryWriter with the code that manually manipulated the file stream.

I got consistent results for numbers, but for strings it was giving weird results. I used the method of write string len (int) and then write string, but the BinaryWriter didn't need that, and when I tried to just use the code that used it, it gave obvious shift errors.

I pulled out reflector and checked out the code.  The magic is in Write7BitEncodedIntit handles splitting an integer into 7 bits, and use the last bit as a progress indication. After reading that and Read7BitEncodedInt, it was clear, and very clever.

I was good to get down on such a problem, at least I haven't lost all sense for bit twiddling code.

Can't say the same for my UI / JavaScript code, however, spent nearly the whole week doing nothing of value, as far I as feel. I am considering moving to C++ again, hibernate++, anyone? :-)*

* For the humor impaired, the last paragraph is a joke, I don't really intent to port hibernate to C++.