学用 ASP.Net 之 System.BitConverter 类


使用 BitConverter 类的一组静态方法可以把一个整数、浮点数、字符或布尔值转换成一个 Byte[], 当然也可逆转.

  主要成员:

/* 字段 */ 
BitConverter.IsLittleEndian //布尔值, 表示当前系统的字节顺序, 在 Windows 下此值是 true 
 
/* 静态方法 */ 
BitConverter.GetBytes() //获取指定参数的 Byte[], 参数类型可以是: Boolean、Char、Double、Int16、Int32、Int64、Single、UInt16、UInt32、UInt64 
 
BitConverter.ToBoolean() //将 Byte[] 转换到布尔值 
BitConverter.ToChar()   //... 
BitConverter.ToDouble() // 
BitConverter.ToInt16()  // 
BitConverter.ToInt32()  // 
BitConverter.ToInt64()  // 
BitConverter.ToSingle() // 
BitConverter.ToUInt16() // 
BitConverter.ToUInt32() // 
BitConverter.ToUInt64() // 
 
BitConverter.ToString() //将 Byte[] 转换为用十六进制表示的字符串 
 
BitConverter.DoubleToInt64Bits() //将 Double 转换为 Int64 表示 
BitConverter.Int64BitsToDouble() //将 Int64 转换为 Double 表示 

  Int -> Byte[] -> Int:

protected void Button1_Click(object sender, EventArgs e) 
{ 
   //把一个 int 转换为 Byte[] 
   int n1 = 0x1F2F3F4F; // n1 = 523190095; 
   byte[] bs = BitConverter.GetBytes(n1); 
 
   //查看 Byte[] 的十六进制表示 
   string s1 = BitConverter.ToString(bs); //4F-3F-2F-1F 
 
   //再转回 int 
   int n2 = BitConverter.ToInt32(bs, 0); //523190095 
 
   TextBox1.Text = string.Concat(n1, "\n", s1, "\n", n2); 
} 

  Double -> Byte[] -> Int64:

protected void Button1_Click(object sender, EventArgs e) 
{ 
   double pi = 3.1415926; 
   byte[] bs = BitConverter.GetBytes(pi);  //4A-D8-12-4D-FB-21-09-40 
   Int64 num = BitConverter.ToInt64(bs, 0); //4614256656431372362 
 
   TextBox1.Text = string.Concat(pi, "\n", BitConverter.ToString(bs), "\n", num); 
} 
 
//使用 DoubleToInt64Bits() 方法可一步完成上面的转换 
protected void Button2_Click(object sender, EventArgs e) 
{ 
   double pi = 3.1415926; 
   Int64 num = BitConverter.DoubleToInt64Bits(pi); //4614256656431372362 
 
   TextBox1.Text = string.Concat(pi, "\n", num); 
} 
 
//下面这种转换是改变了字节序列的 
protected void Button3_Click(object sender, EventArgs e) 
{ 
   double pi = 3.1415926; 
   Int64 num = Convert.ToInt64(pi); //3 
 
   TextBox1.Text = num.ToString(); 
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3