2

I am trying to recreate C#'s BinaryWriter's Write function on a string in Java.
The C# method writes a string's length encoded in 7-bit format, and then the string. Is there any way I can implement this in Java?
I've tried implementing it like so, to no success:

long v = value & 0x00000000ffffffffL;
while (v >= 0x80) {
  writeByte((byte) (v | 0x80));
  v >>= 7;
}
writeByte((byte) v);
lanour
  • 123
  • 1
  • 5
  • Do you have any reference to this 7-bit encoded format? If I lookup BinaryWriter.write it is only mentioned that the length is written as an unsigned integer, no mention of this 7-bit encoded format. https://msdn.microsoft.com/en-us/library/yzxa6408(v=vs.110).aspx – Erwin Bolwidt Jun 12 '15 at 08:09
  • In BinaryWriter.Write's source, the method Write7BitEncodedInt is called on the string length. http://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,2daa1d14ff1877bd – lanour Jun 12 '15 at 08:15
  • That's clear. Surprised that his is not mentioned in the documentation. What is the problem with your above code; in what way does the output differ from the same function in C# ? – Erwin Bolwidt Jun 12 '15 at 08:23
  • @ErwinBolwidt, I tried writing two strings, one with my Java implementation and one with the C# implementation. The C# string is slightly different, it has an odd symbol at the end. – lanour Jun 12 '15 at 08:59
  • I tried your code and it works like I would expect it to. Can you post a hex dump (only of the encoded length portion) of a case where you have a difference between Java and C#? – Erwin Bolwidt Jun 12 '15 at 09:05
  • http://pastie.org/pastes/10236918/text – lanour Jun 12 '15 at 09:18
  • I dont have time to poke at this but I am going to bet that your getting different values because C#'s `byte` is unsigned where as Java's is not, I think if you change `byte` to `sbyte` on the C# code you will at least get the same output (correct or not). – ug_ Jun 12 '15 at 09:37
  • @lanour what data were you writing there? the data starts with a 00 (zero) byte which shouldn't be possible unless the length was zero. – Erwin Bolwidt Jun 12 '15 at 10:00
  • See implementation in [this answer](https://stackoverflow.com/a/12889458/) on the duplicate question. – Peter Duniho Jun 13 '15 at 04:53

0 Answers0