How to Convert byte[4] into int32?

  • Thread starter Thread starter William Stacey
  • Start date Start date
W

William Stacey

Pin the int32 variable, then use Marshal.Copy to copy the contents of the
byte array to the int32 address.

If the array is pinned, you could also cast the first byte to an int pointer
and assign it to a managed int or use it. As you said, you need to be aware
of the endianess. I have also cast structs to byte arrays this way for easy
access to the elements.
 
Hi, this may seem silly, but I really wanna know how to convert a byte[4]
into a int32. This two should be equivalent in the view of bits.

Thanks!
 
Pin the int32 variable, then use Marshal.Copy to copy the contents of the
byte array to the int32 address.

The other alternative (which uses no unsafe code), is to use a combination
of Shift and bitwise Or operators to shift the octet bits into the int32.

The third option (easiest, and also doesn't use unsafe code) is to use the
BitConverter.ToInt32 method.

In any case, you need to be careful about whether the byte array octet order
is big or little endian.

-Rob
 
Back
Top