At least three methods can be used for conversion (see list 1 ). In the system namespace Of the. NET Framework class library, there is a class called bitconverter, which is specially used for this conversion. It has a getbytes method. For most simple types, this method is overloaded. It can return a byte array to save the value you passed. It also has several totypename methods used to convert a byte array into a basic type (primitive type): byte [] B = bitconverter. getbytes (
0xba5eba11 );
// {0x11, 0xba, 0x5e, 0xba}
Uint u = bitconverter. touint32 (
New byte [] {0xfe, 0x5a, 0x11,
0xfa}, 0); // 0xfa115afe
When using bitconverter classes, one important thing to remember is that its behavior depends on the hardware architecture (CodeEndianness (run on the hardware architecture)-that is, the storage order of integer bytes in the memory. If you save the bit as a file format that can be read on many different platforms, there will be problems. Bitconverter has a public islittleendian field. You can check how it runs, but unfortunately you cannot change it.
You can also use manual shift (bit shifting) instead of bitconverter class for conversion: B = new byte [] {0xfe, 0x5a, 0x11, 0xfa };
U = (uint) (B [0] | B [1] <8 |
B [2] <16 | B [3] <24 );
B [0] = (byte) (u );
B [1] = (byte) (U> 8 );
B [2] = (byte) (U> 16 );
B [3] = (byte) (U> 24 );
This method can avoid the problem of byte order, because the location of the byte can be fully controlled.
Finally, if you don't mind using unsafe code, you can use direct memory copy to convert a pointer pointing to the byte array into an integer pointer, then take its value (dereference): unsafe {
Fixed (byte * pb = B)
U = * (uint *) Pb );
}
Like bitconverter, the running result of this method depends on the hardware on which the Code runs.
If you want to perform many such conversions-such as in a loop-and want the best performance, we recommend that you use one of the last two methods. Bitconverter is somewhat slow, although the difference is not big. -- M.S.