使用 BitConverter 類的一組靜態方法可以把一個整數、浮點數、字元或布爾值轉換成一個 Byte[], 當然也可逆轉.
主要成員:
/* 欄位 */BitConverter.IsLittleEndian //布爾值, 表示當前系統的位元組順序, 在 Windows 下此值是 true/* 靜態方法 */BitConverter.GetBytes() //擷取指定參數的 Byte[], 參數類型可以是: Boolean、Char、Double、Int16、Int32、Int64、Single、UInt16、UInt32、UInt64BitConverter.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();}