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.
"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:
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.
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.
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