int跟byte[]数组互转的方法,整数 + 浮点型

整数:

int转byte数组

 public static byte[] intToBytes2(int n){
       byte[] b = new byte[4];
      
       for(int i = 0;i < 4;i++)
       {
        b[i]=(byte)(n>>(24-i*8));
     
   } 
   return b;
 } 
byte转换为int
public static int byteToInt2(byte[] b) {

                   int mask=0xff;
                   int temp=0;
                   int n=0;
                   for(int i=0;i<b.length;i++){
                      n<<=8;
                      temp=b[i]&mask;
                      n|=temp;
                  }
         return n;
    }

浮点:

 /// <summary>
        /// 16进制转换为10进制浮点数
        /// </summary>
        /// <param name="instr"></param>
        /// <returns></returns>
        public static string ByteToFloat(string instr)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(instr))
            {
                byte[] floatVals1 = StringToBytes(instr);
                result = BitConverter.ToSingle(floatVals1, 0).ToString();
            }
            return result;

        }
        /// <summary>
        /// 16进制转换为10进制整数
        /// </summary>
        /// <param name="instr"></param>
        /// <returns></returns>
        public static string ByteToInt(string instr)
        {
            string result = string.Empty;
            int n = 0;
            if (!string.IsNullOrEmpty(instr))
            {
                byte[] b = StringToBytes(instr);
                int mask = 0xff;
                int temp = 0;

                for (int i = 0; i < b.Length; i++)
                {
                    n <<= 8;
                    temp = b[i] & mask;
                    n |= temp;
                }
            }
            return result = n.ToString();

        }

        /// <summary>
        /// 把一个存储16进制数的字符串转化为存储16进制数的字节数组
        /// </summary>
        /// <param name="HexString">存储16进制数的字符串</param>
        /// <returns>返回一个字节数组</returns>
        public static byte[] StringToBytes(string HexString)
        {
            byte[] temdata = new byte[HexString.Length / 2];
            for (int i = 0; i < temdata.Length; i++)
            {
                temdata[i] = Convert.ToByte(HexString.Substring(i * 2, 2), 16);
            }
            return temdata;
        }
        /// <summary>
        /// 去除字符串中所有的空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveAllSpace(string str)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(str))
            {
                result = Regex.Replace(str, @"\s+", "");
            }
            return result;
        }

 http://www.cnblogs.com/jhabb/archive/2011/05/06/2038777.html

posted on 2013-12-03 15:15  小东北  阅读(27675)  评论(0编辑  收藏  举报