随笔 - 2146  文章 - 19 评论 - 11846 阅读 - 1267万


使用 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();
}

posted on   万一  阅读(2472)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2010-01-06 RegularExpressions(2) RegularExpressions 支持的正则表达式语法
2008-01-06 Delphi 中的 XMLDocument 类详解(17) - 上一个节点、下一个节点、父节点


点击右上角即可分享
微信分享提示