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
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
When the elements of mybyte are of type Byte, doing mybyte(0)) << 24 results in a Byte, which is no good because all the bits get lost. That operator gives a result of the same type as the left operand.
You need to convert each element to the type you want to get out at the end:
Dim a = CUInt(mybyte(0)) << 24 Or CUInt(mybyte(1)) << 16 Or CUInt(mybyte(2) << 8) Or mybyte(3)
(Arithmetic bit shift has a higher precedence than bitwise operators. The final byte doesn't need to be converted to a different type.)
There was some inconsistency in the question as to whether an integer or unsigned integer was needed: change the occurrences of CUInt to CInt if the former.
If you use * and + operators, you could do
Dim b = (((mybyte(0) * 256 + mybyte(1)) * 256) + mybyte(2)) * 256 + mybyte(3)
or
Dim c = mybyte(0) * 16777216 + mybyte(1) * 65536 + mybyte(2) * 256 + mybyte(3)
which work without conversions because the multipliers 16777216, 65536, and 256 are of type Integer.
Or you could just use:
Dim n = BitConverter.ToInt32(mybyte.Reverse().ToArray(), 0)
Finally, if you're using .NET Core 2.1 or later, it's really easy:
Dim d = BinaryPrimitives.ReadInt32BigEndian(mybyte)
Docs: BinaryPrimitives Class—"Use these helpers when you need to read specific endianness."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With