您的位置:首页 > 其它

通信协议 数据写入字节数组的辅助类ProtocolHelper2

2011-10-29 09:36 351 查看
public static int AddUTF8StringToBuf1(ref Byte[] buf, int start, string str)
{
byte[] bytes;

bytes = Encoding.UTF8.GetBytes(str);

return AddDataToBuf1(ref buf, start, bytes, (Byte)bytes.Length);
}

public static int AddStringToBuf1(ref Byte[] buf, int start, string str)
{
int i, p;
Byte len;

p = start;

len = (Byte)str.Length;

buf[p++] = len;

for (i = 0; i < len; )
{
buf[p++] = System.Convert.ToByte(str[i++]);
}

return (int)(len + 1);
}

public static int AddDataToBuf1(ref Byte[] buf, int start, Byte[] data, int len)
{
int i, p;

p = start;

buf[p++] = (byte)len;

for (i = 0; i < len; )
{
buf[p++] = data[i++];
}

return (int)(len + 1);
}

public static int AddDataToBuf2(ref Byte[] buf, int start, Byte[] data, int len)
{
int i, p;

p = start;

if (len > 1024) return start;

buf[p++] = (Byte)(len >> 8);
buf[p++] = (Byte)len;

for (i = 0; i < len; )
{
buf[p++] = data[i++];
}

return (int)(len + 2);
}

public static int AddValueToBuf(ref Byte[] buf, int start, uint value, int len)
{
Byte i;
int p;

if (len < 1 || len > 4) return start;

p = start;

for (i = 0; i < len; i++)
{
buf[p++] = (Byte)(value >> ((len - i - 1) * 8));
}

return len;
}

public static int AddUlongValueToBuf(ref Byte[] buf, int start, ulong value, int len)
{
Byte i;
int p;

if (len < 1 || len > 8) return 0;

p = start;

for (i = 0; i < len; i++)
{
buf[p++] = (Byte)(value >> ((len - i - 1) * 8));
}

return len;
}

public static int AddDateTimeToBuf(ref Byte[] buf, int start, DateTime time, int len)
{
int p;

p = start;

buf[p++] = (Byte)(time.Year-2000);
buf[p++] = (Byte)(time.Month);
buf[p++] = (Byte)(time.Day);
buf[p++] = (Byte)(time.Hour);
buf[p++] = (Byte)(time.Minute);
buf[p++] = (Byte)(time.Second);

return 6;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: