Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does BitConverter.ToInt32 work?

Here is a method -

using System;

class Program
{
    static void Main(string[] args)
    {
        //
        // Create an array of four bytes.
        // ... Then convert it into an integer and unsigned integer.
        //
        byte[] array = new byte[4];
        array[0] = 1; // Lowest
        array[1] = 64;
        array[2] = 0;
        array[3] = 0; // Sign bit
        //
        // Use BitConverter to convert the bytes to an int and a uint.
        // ... The int and uint can have different values if the sign bit differs.
        //
        int result1 = BitConverter.ToInt32(array, 0); // Start at first index
        uint result2 = BitConverter.ToUInt32(array, 0); // First index
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.ReadLine();
    }
}

Output

16385 16385

I just want to know how this is happening?

like image 507
user1027508 Avatar asked Nov 03 '11 11:11

user1027508


2 Answers

The docs for BitConverter.ToInt32 actually have some pretty good examples. Assuming BitConverter.IsLittleEndian returns true, array[0] is the least significant byte, as you've shown... although array[3] isn't just the sign bit, it's the most significant byte which includes the sign bit (as bit 7) but the rest of the bits are for magnitude.

So in your case, the least significant byte is 1, and the next byte is 64 - so the result is:

( 1 * (1 << 0) ) +    // Bottom 8 bits
(64 * (1 << 8) ) +    // Next 8 bits, i.e. multiply by 256
( 0 * (1 << 16)) +    // Next 8 bits, i.e. multiply by 65,536
( 0 * (1 << 24))      // Top 7 bits and sign bit, multiply by 16,777,216

which is 16385. If the sign bit were set, you'd need to consider the two cases differently, but in this case it's simple.

like image 112
Jon Skeet Avatar answered Nov 05 '22 00:11

Jon Skeet


It converts like it was a number in base 256. So in your case : 1+64*256 = 16385

like image 45
Toto Avatar answered Nov 04 '22 23:11

Toto