在上次做的项目中,使用到了Socket进行数据通讯,其中用到了一些数据类型进行转换的方法,现在

贴出来给大家分享下,希望大家多给些意见,能进一步帮忙完善更好了,先谢过了。

 

 /// <summary>
        /// 整数转为Byte【】
        /// 低位在前,高位在后
        /// </summary>
        /// <param name="r">要转换的整数</param>
        /// <param name="digits">Byte位数</param>
        /// <returns></returns>
        private static byte[] GetBytesFromInt(int r, int digits)
        {
            byte[] bt = new byte[digits];
            int j=8;
            for (int k = 0; k < digits; k++)
            {
                j=8*k;
                bt[k]=(byte)(r>>j);
            }
            return bt;
        }
     
        /// <summary>
        /// 将字符转换为Byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static byte[] GetBytesFromStr(string s)
        {
            byte[] bt = Encoding.UTF8.GetBytes(s);
            return bt;
        }
        /// <summary>
        /// 计算字符传编码时的字节长度
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static int GetBytesLengthFromStr(string s)
        {
            int iLength = Encoding.UTF8.GetByteCount(s);
            return iLength;
        }

        /// <summary>
        /// 将Byte数组转化为Int16
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        private static Int16 GetInt16FromBytes(byte[] bt)
        {
            Int16 s = BitConverter.ToInt16(bt,0);
            return s;
        }

        /// <summary>
        /// 将Byte数组转化为Int32
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        private static int GetIntFromBytes(byte[] bt)
        {
            int s = BitConverter.ToInt32(bt, 0);
            return s;
        }

        /// <summary>
        /// 将Byte数组转化为String
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        private static string GetStrFromBytes(byte[] bt)
        {
            string s = BitConverter.ToString(bt, 0);
            return s;
        }