-1

I've been trying to figure out how mscorlib Convert.ToInt32(byte) works given I only have access to .Net 2.0 for a project. Trying to use a .Net reflector to open that dll has resulted in no help so far in trying to see how .Net handled it in .Net 4.5 (which again, I don't have access to for this project).

Could someone explain how Convert.ToInt32(byte) works to convert and create a 32 bit signed int from a byte and how in code I can do this?

I've noticed there is a huge difference in the code below. Is it just a lower and upper bounds set for int32 and returns 0 if outside?

Console.WriteLine(
     Convert.ToInt32(buffer[i]).ToString() + 
                                         " " + 
     BitConverter.ToInt32(buffer, i).ToString()
 );

Convert.ToInt32 vs BitConverter.ToInt32

Euthyphro
  • 700
  • 1
  • 9
  • 26

3 Answers3

3

From MSDN documentation https://msdn.microsoft.com/en-us/library/system.bitconverter.toint32(v=vs.80).aspx

BitConverter.ToInt32 takes 4 bytes starting at the position in the array you give it and converts it to a signed integer.

Convert.ToInt32 takes 1 byte and "expands" it to a Int32 type.

Given a byte array of length 4, called buffer, then BitConverter.ToInt32(buffer, 0)

would compute the following:

buffer[3] * 16777216 + buffer[2] * 65536 + buffer[1] * 256 + buffer[0]

Convert.ToInt32(buffer[0]) on the other hand would compute the following:

(Int32)buffer[0]
DanL
  • 1,974
  • 14
  • 13
1

BitConverter.ToInt32(byte[] buffer, int index) always takes 4 bytes, Convert.ToInt32(byte b) takes just 1.

w.b
  • 11,026
  • 5
  • 30
  • 49
0

Convert.ToInt32() converts a specified value to a 32-bit signed integer. while BitConvertor.ToInt32() returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.

Here is the MSDN documentation for both with exampleBitConvertor

Convert.ToInt32

WAQ
  • 2,556
  • 6
  • 45
  • 86