c# - How to extend string to deserialize binary data -
i'm using own extension method serialize strings (and more data types) file custom binary format (external, cannot modify format). method is:
public static byte[] serialize(this string str) { if (str.length > short.maxvalue) throw new argumentoutofrangeexception("str", "max length allowed " + short.maxvalue.tostring()); list<byte> data = new list<byte>(); data.add(0); data.add(0); if (str != null) { byte[] buffer = encoding.utf8.getbytes(str); data.addrange(buffer); data[0] = (byte)(buffer.length % 256); data[1] = (byte)((buffer.length / 256) >> 8); } return data.toarray(); }
an example of usage:
string str1 = "binary string"; byte[] data = str1.serialize();
result is
data = { 13, 0, 66, 105, 110, 97, 114, 121, 32, 83, 116, 114, 105, 110, 103 }
now i'm trying add extension method deserialize when reading these files:
public static void deserialize(this string str, byte[] data) { if (data == null || data.length < 2) { str = null; } else { short length = (short)(data[0] + (data[1] << 8)); if (data.length != length + 2) throw new argumentexception("invalid data", "data"); str = encoding.utf8.getstring(data, 2, length); } }
if try this:
string str2 = null; str2.deserialize(data);
the expected result str2 is
"binary string"
the actual result is
null
however, when debugging step step, str
inside deserialize()
gets correct value @ line str = encoding.utf8.getstring(data, 2, length);
.
also tried this:
string str3 = string.deserialize(data);
but not compile, , error message is
error 1 'string' not contain definition 'deserialize'
i don't know i'm doing wrong. idea on how solve it?
the first parameter of extension method object acting on. in case byte array data
. return type wanting stuff string variable. therefore, signature deserialize
method should be:
public static string deserialize(this byte[] data)
also inside method need return string value full method should (note simplified slightly):
public static string deserialize(this byte[] data) { if (data == null || data.length < 2) return null; short length = (short)(data[0] + (data[1] << 8)); if (data.length != length + 2) throw new argumentexception("invalid data", "data"); return encoding.utf8.getstring(data, 2, length); }
and use this:
string str1 = "binary string"; byte[] data = str1.serialize(); string str2 = data.deserialize();
Comments
Post a Comment