Mattias Sjogren describes the mutual conversion between int and byte. See convert integer to byte array. In fact, there are still many methods. Here, I have summarized four methods, including Mattias Sjogren.
Mutual conversion between int and byte [] Mu Feng wangzhi
1. The most common method
- From byte [] to uint B = New Byte [] {0xfe,0x5a,0x11,0xfa} ;
U = ( Uint ) (B [ 0 ] | B [ 1 ] < 8 | B [ 2 ] < 16 | B [ 3 ] < 24 );
- From int to byte [] B [ 0 ] = ( Byte ) (U );
B [ 1 ] = ( Byte ) (U > 8 );
B [ 2 ] = ( Byte ) (U > 16 );
B [ 3 ] = ( Byte ) (U > 24 );
2. Use bitconverter (strongly recommended)
- From int to byte []Byte[] B=Bitconverter. getbytes (
0xba5eba11);
//{0x11, 0xba, 0x5e, 0xba}
- From byte [] to int Uint U = Bitconverter. touint32 (
New Byte [] {0xfe,0x5a,0x11,
0xfa} , 0 ); // 0xfa115afe
3. UnsafeCode(Though simple, you need to change the compilation options)
Unsafe
{
// From int to byte []
Fixed ( Byte * PB = B );
// From byte [] to int
U = * (( Uint * ) Pb );
}
4. Use the marshal class
Intptr = Marshal. allochglobal ( 4 ); // Allocate unmanaged memory
Byte [] B = New Byte [ 4 ] {1,2,3,4} ;
// From byte [] to int
Marshal. Copy (B, 0 , PTR, 4 );
Int U = Marshal. readint32 (PTR );
// From int to byte []
Marshal. writeint32 (PTR, U );
Marshal. Copy (PTR, B, 0 , 4 );
Marshal. freehglobal (PTR ); // Remember to release the memory
It seems troublesome to use the 4th types. In fact, if you want to convert the structure (struct) type to byte [], the 4th types are quite convenient. For example:
Int Len = Marshal. sizeof ( Typeof (Mystruct ));
Mystruct O;
Byte [] Arr = New Byte [Len]; // {};
Intptr = Marshal. allochglobal (LEN );
Try
{
// From byte [] to struct mystruct
Marshal. Copy (ARR, index, PTR, math. Min (length, arr. Length - Index ));
O = (Mystruct) Marshal. ptrtostructure (PTR, Typeof (Mystruct ));
// From struct mystruct to byte []
Marshal. structuretoptr (O, PTR, True ); // Pay attention to the fdeleteold parameter during use
Marshal. Copy (PTR, arr, 0 , Len );
}
Finally
{
Marshal. freehglobal (PTR );
}
Return O;