This is an example of how you can send a byte[ ] over the wire by manually packing it into a string, this can be useful when you need to send an array or list of items over an RPC call for example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
[StructLayout(LayoutKind.Explicit)]
struct byte2char
{
[FieldOffset(0)]
public byte b1;
[FieldOffset(1)]
public byte b2;
[FieldOffset(0)]
public char c;
}
public static class str_transmitter
{
static byte2char bc = new byte2char();
public static string b2s(byte[ ] data)
{
if (data.Length % 2 != 0)
throw new Exception("Data must be divisable by two");
var chars = new char[data.Length / 2];
var j = 0;
for (var i = 0; i < data.Length; i += 2)
{
bc.b1 = data[i];
bc.b2 = data[i + 1];
chars[j] = bc.c;
++j;
}
return new String(chars);
}
public static byte[ ] s2b(string s)
{
var chars = s.ToCharArray();
var data = new byte[chars.Length * 2];
var j = 0;
for (var i = 0; i < data.Length; i += 2)
{
bc.c = chars[j];
data[i] = bc.b1;
data[i + 1] = bc.b2;
++j;
}
return data;
}
}
class Program
{
static void Main(string[ ] args)
{
var p = 0;
var d = new byte[256 * 256 * 2];
for (byte i = 0 ;; ++i)
{
for (byte j = 0 ;; ++j)
{
d[p] = i;
d[p+1] = j;
p += 2;
if (j == 255)
break;
}
if (i == 255)
break;
}
var str = str_transmitter.b2s(d);
var x = str_transmitter.s2b(str);
Console.WriteLine("xed_data.Length = " + x.Length);
Console.WriteLine("org_data.Length = " + d.Length);
for (var i = 0; i < d.Length; ++i)
{
if (d[i] != x[i])
{
Console.WriteLine("error: " + i);
}
}
Console.WriteLine("All checked");
Console.ReadLine();
}
}
}