At some times, we need to convert 32-bit int data into byte data for transmission and storage.
In this case, the 32-bit int type data needs to be transferred to the byte array of 4 bytes, or to the 32-bit int type data from the byte array of 4 bytes.
In C/C ++, we can use the memcpy () function directly, however, in C #, no function can directly convert 32-bit int data into byte data.
C #: 32-bit int-type data is converted into 4 bytes of byte data
////// Convert int32 data to a byte array of 4 bytes //////Int32 data///Byte array of 4 bytes///
Static bool ConvertIntToByteArray (Int32 m, ref byte [] arry) {if (arry = null) return false; if (arry. length <4) return false; arry [0] = (byte) (m & 0xFF); arry [1] = (byte) (m & 0xFF00)> 8 ); arry [2] = (byte) (m & 0xFF0000)> 16); arry [3] = (byte) (m> 24) & 0xFF ); return true ;}
Call method:
byte [] buf = new byte[4];bool ok = ConvertIntToByteArray(0x12345678, ref buf);
In this way, 32-bit int data can be converted into 4 bytes of byte data.
In turn, BitConverter. ToInt32 can be directly used for implementation:
Int32 dd = BitConverter.ToInt32(buf, 0);
Buf is the previously used buf.
C/C ++ converts 32-bit int data to BYTE []
Int --> BYTE []
int data = 0xFFFFFFFF;unsigned char buf[4];memcpy(buf, &data, sizeof(int));
BYTE [] --> int
memcpy(&data, buf, 4);
The implementation of this conversion is not difficult, as long as you have mastered the data storage format.
Mark it!