views:

9677

answers:

4

I'm wonder what the best way to convert a byte array (length 4) to an integer is in vb.net? I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory. Along the same lines, what about converting a single/double from it's binary representation to an single/double variable.

+17  A: 

"Copying bytes of memory" is something that .NET isn't particularly suited for (and VB.NET even less so). So, unless switching to C is an option for you, a function call is pretty much unavoidable for this.

BitConverter is a well-thought-out, tested function. Of course, you can avoid it by doing something like (in C#):

myInt = (*pbyte) | (*(pbyte + 1) << 8)  | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);

(which is, incidentally, exactly what BitConverter does for you when converting a byte array to an Integer...).

However, this code:

  • Is much, much harder to read and understand than the BitConverter equivalent;
  • Doesn't do any of the error checking that BitConverter does for you;
  • Doesn't differentiate between little-endian and big-endian representations, like BitConverter does.

In other words: you might "save" a function call, but you will be significantly worse off in the end (even assuming you don't introduce any bugs). In general, the .NET Framework is very, very well designed, and you shouldn't think twice about using its functionality, unless you encounter actual (performance) issues with it.

mdb
+1  A: 

mdb is exactly correct, but, here is some code to convert a vb byte array to little endian integer anyway...(just in case you wish to write your own bitconverter class)

' where bits() is your byte array of length 4

Dim i as Integer 

i = (((bits(0) Or (bits(1) << 8)) Or (bits(2) << &H10)) Or (bits(3) << &H18))
sbeskur
VB.NET supports the bit-shift operators? I never knew that ...
John Rudy
I believe it has been supported since 1.1 (VB.NET 2003).
sbeskur
A: 

You can block copy byte[] to int[] using System.Buffer class.

Orlangur
care to expand? sounds interesting
divinci
+5  A: 

I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory.

Whereas I view the situation as "it seems quite a waste trying to hand-code an efficient way of doing this when there's already a method call which does exactly what I want."

Unless you're absolutely convinced that you have a performance bottleneck in this exact piece of code, use the functionality provided by the framework.

Jon Skeet