Byte array to a number

Hello!

I am wondering how I can convert an array of bytes into an integer or a long or any other number datatype. For example,

byte[] someArray = new byte[] { 0xFF, 0x4A, 0xC2, 0x21 };

How could I turn that into 0xFF4AC221, so that I can perform normal numerical operations on it



Answer this question

Byte array to a number

  • Fradam

    Well, it was just an arbitrary example.  I'm basically asking how I can take the bytes from a 4-byte array and put them together in the same order they occur in. I figured something like shifting would help, but I've never been able to wrap my head around shifting bits for whatever reason.
  • World

    One obvious way would be to use shift operators, as in

    long myNum = someArray[0] << 24 + someArray[1] << 16 + someArray[2] << 8 + someArray[3];

    You could also write a loop to do this. Where is the data coming from Are you sure the bytes are in that order



  • Aqib

    Check out the BitConverter class http://msdn2.microsoft.com/en-us/library/system.bitconverter.aspx

    In your particular case you'd call BitConverter.ToInt32 or BitConverter.ToUInt32. 


    i = BitConverter.ToInt32(someArray, 0);
     

    Note however that i will most likely have the value 0x21C24AFF because Intel processors are little-endian and BitConveter (on Intel at least) takes array[0] to be the least significant byte. 

    You can use BitConverter.IsLittleEndian to discover whether the platform you are running on is little-endian or big-endian.  If the contents of the byte array don't match BitConverter's expectations the easiest way to swap the bytes is to use Array.Reverse


    Array.Reverse(someArray);
     

    I have no actual experience with BitConverter on a big-endian processor but this blog indicates that it puts the most significant byte in array [0].  http://blogs.msdn.com/robunoki/archive/2006/04/05/568737.aspx


  • skilled_desinger

    This is exactly what I was looking for. :) Thanks a lot!
  • Byte array to a number