INT and BYTE [] Mutual conversion

xiaoxiao2021-03-05  19

About INT and BYTE [] Mattias Sjogren introduced three ways. See "Convert Integer into Byte Array". In fact, there should be many ways. Here, I summarized four ways including Mattias Sjogren.

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 Intuint U = Bitconverter.touint32 (New Byte [] {0xfe, 0x5a, 0x11, 0xfa}, 0); // 0xfa115afe

3. UNSAFE code (although simple, you need to change compilation options)

Unsafe {// from int to byte [] fixed (byte * pb = b)

// From Byte [] to INT u = * ((UINT *) PB);

4. Using the Marshal class

INTPTR PTR = Marshal.allochglobal (4); // To assign 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 (PT); // from int to byte [] Marshal.WriteInt32 (PTR, U); Marshal.copy (PTR, B, 0, 4); Marshal. FreeHGLOBAL (PTR); // Finally, remember to release memory

It is quite convenient to use the fourth type to look more troubleshot, in fact, if you want to convert the structure type to BYTE [], the fourth is quite convenient. E.g:

INT LEN = Marshal.sizeOf (TypeOf (MyStruct)); MyStruct O; Byte [] arr = new byte [len]; // {...};

INTPTR PTR = 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); // should pay attention to fdleteold parameters Marshal.copy (PTR, Arr, 0, LEN);} Finally {Marshal.Freehglobal (PTR) } Return o;

转载请注明原文地址:https://www.9cbs.com/read-38605.html

New Post(0)