int 与 byte[] 的相互转换

关于 int 与 byte[] 的相互转换,Mattias Sjogren 介绍了3种方法。请参见 《将Integer转换成Byte Array》。其实应该还有不少方法。在这里,我归纳了包括Mattias Sjogren在内的4种方法。

int 与 byte[] 的相互转换    沐枫网志


1. 最普通的方法

  • 从byte[] 到 uint 
    ExpandedBlockStart.gif ContractedBlock.gif =   new   byte []  dot.gif {0xfe,0x5a,0x11,0xfa} ;
    None.gif
    =  ( uint )(b[ 0 |  b[ 1 <<   8   |  b[ 2 <<   16   |  b[ 3 <<   24 );
  • 从int 到 byte[]
    None.gif b[ 0 =  ( byte )(u);
    None.gifb[
    1 =  ( byte )(u  >>   8 );
    None.gifb[
    2 =  ( byte )(u  >>   16 );
    None.gifb[
    3 =  ( byte )(u  >>   24 );
    None.gif

2. 使用 BitConverter (强力推荐)

  • 从int 到byte[]
    None.gif byte [] b  =  BitConverter.GetBytes(
    None.gif   
    0xba5eba11  ); 
    None.gif
    // {0x11,0xba,0x5e,0xba}
     
  • 从byte[]到int
    None.gif uint  u  =  BitConverter.ToUInt32(
    ExpandedBlockStart.gifContractedBlock.gif   
    new   byte []  dot.gif {0xfe0x5a0x11
    ExpandedBlockEnd.gif   
    0xfa}
    , 0  );  //  0xfa115afe

3. Unsafe代码 (虽然简单,但需要更改编译选项)


None.gif unsafe  
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
// 从int 到byte[]
InBlock.gif
fixed ( byte* pb = b );
InBlock.gif
// 从byte[] 到 int
InBlock.gif
= *((uint*)pb);
ExpandedBlockEnd.gif}

4. 使用Marshal类    
None.gif IntPtr ptr  =  Marshal.AllocHGlobal( 4 );  //  要分配非托管内存
ExpandedBlockStart.gifContractedBlock.gif
     byte [] b =   new   byte [ 4 ] dot.gif {1,2,3,4} ;
None.gif
// 从byte[] 到 int
None.gif
    Marshal.Copy(b,  0 , ptr,  4 );
None.gif    
int  u  =  Marshal.ReadInt32(ptr); 
None.gif
// 从int 到byte[]
None.gif
    Marshal.WriteInt32(ptr, u);
None.gif    Marshal.Copy(ptr,b,
0 , 4 );
None.gif    Marshal.FreeHGlobal(ptr); 
//  最后要记得释放内存

 

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

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

None.gif    IntPtr ptr 
=  Marshal.AllocHGlobal(len);
None.gif    
try
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif
// 从byte[] 到struct MyStruct
InBlock.gif
     Marshal.Copy(arr, index, ptr, Math.Min(length, arr.Length - index));
InBlock.gif     o 
= (MyStruct)Marshal.PtrToStructure(ptr, typeof(MyStruct));
InBlock.gif
InBlock.gif
InBlock.gif
// 从struct MyStruct 到 byte[]
InBlock.gif
     Marshal.StructureToPtr(o, ptr, true); // 使用时要注意fDeleteOld参数
InBlock.gif
     Marshal.Copy(ptr, arr, 0, len);
ExpandedBlockEnd.gif    }

None.gif    
finally
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif     Marshal.FreeHGlobal(ptr);
ExpandedBlockEnd.gif    }

None.gif    
return  o;
None.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值