Search code examples
c#vb.netbit-manipulationconverters

VB.NET Convert 4 bytes to an integer


Windows 11 U.S.

VB.NET, How can I convert 4 bytes in a byte array to an integer value?

I can figure out how to do two bytes using something like

IntValue = (mybyte(0) * 256) Or mybyte(1)

So if mybyte(0) = 3 and mybyte(1) = 232, or the hex equiv number 03E8, it would be int=1000.

How can I do this if I have 4 bytes? mybyte(0)..(3).

So if I had myByte(0) = 64 and the rest of the bytes (x) are 0, or the hex equiv number of 40000000, it would equal 1,073,741,824.

I tried other suggestions:

intval = Bitconverter.Toint32(mybyte, 0)

... all I get is 64.

I also tried

Dim combined As UInteger = CType(((mybyte(0) << 24) Or (mybyte(1) << 16) Or (mybyte(2) << 8) Or (mybyte(3) << 0)), UInteger)

... all I get is 64

expecting 1,073,741,824


Solution

  • Since you also tagged C# originally (before the tags were editted), here's a solution in C# (which I assume you can convert easily to VB.NET).

    Using BitConverter that you mentioned is indeed the way to go.

    The following example is based on the documentation from MS: How to convert a byte array to an int:

    byte[] bytes = new byte[] { 64, 0, 0, 0 };
    
    // If the system architecture is little-endian (that is, little end first),
    // reverse the byte array.
    if (BitConverter.IsLittleEndian)
        Array.Reverse(bytes);
    
    int i = BitConverter.ToInt32(bytes, 0);
    Console.WriteLine("int: {0}", i);
    

    Output:

    int: 1073741824
    

    Note the proper handling of Endianness to make sure the bytes are treated in the right order.

    Live demo