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

来源:互联网 发布:centos安装pptp 编辑:程序博客网 时间:2024/05/17 23:14
 
 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;        }