在 VB.Net 中将字节数组转换为整数
我想知道在 vb.net 中将字节数组(长度 4)转换为整数的最佳方法是什么? 我知道 BitConverter,但执行函数调用来执行应该可以通过复制 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
.NET 并不特别适合“复制内存字节”(VB.NET 更不适合)。 因此,除非您可以选择切换到 C,否则函数调用几乎是不可避免的。
BitConverter 是一个经过深思熟虑、经过测试的功能。 当然,您可以通过执行类似的操作(在 C# 中)来避免这种情况:(
顺便说一下,这正是 BitConverter 在将字节数组转换为整数时为您所做的事情...)。
然而,这段代码:
换句话说:你可能会“保存”一个函数调用,但最终你的情况会变得更糟(即使假设你没有引入任何错误)。 一般来说,.NET Framework 的设计非常非常好,您不应该在使用它的功能时三思而后行,除非您遇到实际的(性能)问题。
"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#):
(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.
然而我认为这种情况是“当已经有一个方法调用完全符合我的要求时,尝试手动编写一种有效的方法来执行此操作似乎是一种浪费。”
除非您绝对确信这段代码存在性能瓶颈,否则请使用框架提供的功能。
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.
mdb 是完全正确的,但是,这里有一些代码可以将 vb 字节数组转换为小端整数...(以防万一您希望编写自己的位转换器类)
' 其中 bits() 是长度为 4 的字节数组
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
您可以使用 System.Buffer 类阻止将 byte[] 复制到 int[]。
You can block copy byte[] to int[] using System.Buffer class.