Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte Array to Integer In VB.Net

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.

like image 721
Kibbee Avatar asked Nov 27 '22 08:11

Kibbee


2 Answers

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

like image 51
mdb Avatar answered Feb 01 '23 03:02

mdb


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.

like image 41
Jon Skeet Avatar answered Feb 01 '23 01:02

Jon Skeet