您的位置:首页 > 其它

int 与 byte[] 的相互转换 关于 int 与 byte[] 的相互转换,Mattias Sjogren 介绍了3种方法

2009-12-02 14:00 633 查看
1. 最普通的方法

从byte[] 到 uint
u = (uint)(b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24);
从int 到 byte[]
b[0] = (byte)(u);
b[1] = (byte)(u >> 8);
b[2] = (byte)(u >> 16);
b[3] = (byte)(u >> 24);

2. 使用 BitConverter (强力推荐)

从int 到byte[]
byte[] b = BitConverter.GetBytes(
0xba5eba11 );
//{0x11,0xba,0x5e,0xba}
从byte[]到int
uint u = BitConverter.ToUInt32(
unsafe
IntPtr ptr = Marshal.AllocHGlobal(4); // 要分配非托管内存
//从byte[] 到 int
Marshal.Copy(b, 0, ptr, 4);
int u = Marshal.ReadInt32(ptr);
//从int 到byte[]
Marshal.WriteInt32(ptr, u);
Marshal.Copy(ptr,b,0,4);
Marshal.FreeHGlobal(ptr); // 最后要记得释放内存

使用第4种看起来比较麻烦,实际上,如果想把结构(struct)类型转换成byte[],则第4种是相当方便的。例如:

int len = Marshal.Sizeof(typeof(MyStruct));
MyStruct o;
byte[] arr = new byte[len];//{};

IntPtr ptr = Marshal.AllocHGlobal(len);
try
finally
return o;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: