Convert entire byte [] to uint

I have byte [] srno in my code

byte[] srno = new byte[6]; srno[0] = 0xff; srno[1] = 0x0f; srno[2] = 0x24; srno[3] = 0x12; srno[4] = 0x16; srno[5] = 0x0a; 

now i want this value in uint as

 uint a = 0xff0f2412160a; 

How to convert it?

+6
source share
3 answers

As @animaonline suggested, you should use BitConverter to convert a byte array to uint or * ulong. So you have 6 bytes, uint is too small for you. You must convert to ulong *. But the converter requires eight bytes, so create a new array with the required number of bytes:

 byte[] value = new byte[8]; Array.Reverse(srno); // otherwise you will have a1612240fff result Array.Copy(srno, value, 6); ulong result = BitConverter.ToUInt64(value, 0); Console.WriteLine("{0:x}", result); // ff0f2412160a 
+8
source

In the System namespace, you will find the BitConverter library BitConverter . You want to use the static function ToUInt64() as follows:

 var a = BitConvert.ToUInt64(srno, 0); 

You will need to adjust the size of your array to [8]

MSDN

0
source

Everyone seems to ignore the byte-order encoding of its expected result. The BitConverter class uses fixed encoding (usually Little-Endian, IIRC). The output in the example is assumed to be large-endian. In an ideal world, you just do the math yourself, but it's easier to use Array.Reverse and then use the built-in BitConverter class.

There will probably be a bunch of answers before I can post this, so here is a very quick piece of unsafe code:

 public static unsafe ulong ToULong(byte[] values) { byte* buffer = stackalloc byte[8]; if (BitConverter.IsLittleEndian) Array.Reverse(values); System.Runtime.InteropServices.Marshal.Copy(values, 0, (IntPtr)buffer, values.Length); return *(ulong*)buffer; } 
0
source

All Articles