public static byte[] ToBytes(this SFO.DataFormat format, object o) { if (o == null) { throw new Exception("Object cannot be null."); } switch (format) { case SFO.DataFormat.UTF8: return(Encoding.UTF8.GetBytes((string)o)); case SFO.DataFormat.UTF8_TERMINATED: byte[] bytes = Encoding.UTF8.GetBytes((string)o); byte[] terminated = new byte[bytes.Length + 1]; Array.Copy(bytes, 0, terminated, 0, bytes.Length); terminated[bytes.Length] = 0; return(terminated); case SFO.DataFormat.INT32: int i = (int)o; return(new byte[] { (byte)(i & 0xFF), (byte)((i >> 8) & 0xFF), (byte)((i >> 16) & 0xFF), (byte)((i >> 24) & 0xFF) }); default: throw new Exception("Unimplemented data format \"" + format + "\"."); } }
public static object FromBytes(this SFO.DataFormat format, byte[] bytes) { switch (format) { case SFO.DataFormat.UTF8: return(Encoding.UTF8.GetString(bytes)); case SFO.DataFormat.UTF8_TERMINATED: int end = bytes.Length; for (int i = 0; i < bytes.Length; i++) { if (bytes[i] == 0) { end = i; break; } } return(Encoding.UTF8.GetString(bytes, 0, end)); case SFO.DataFormat.INT32: return((bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24)); default: throw new Exception("Unimplemented data format \"" + format + "\"."); } }