Is there a more efficient way to throw 4 bytes into a long one?

Suppose I have a fixed size and long byte array:

Dim abHeader(0 To 3) As Byte
Dim lHeader As Long

      

To pass an array of bytes to Long, with array index 3 located at 8 LSB Long, I am currently using:

lHeader = (CLng(abHeader(0)) << 24) _
       Or (CLng(abHeader(1)) << 16) _
       Or (CLng(abHeader(2)) << 8) _
       Or (CLng(abHeader(3)))

      

Is there a more efficient way to compute to accomplish this task in VB.NET? (It is used in a time-critical cycle.)

NB: Strict option is on.

+3


source to share


2 answers


You can try , then . The class uses C # unsafe code to directly pass an array of bytes to (or it does so at least as long as the parameter is divisible by 4): BitConverter.ToInt32()

CLng()

BitConverter

Integer

startIndex

Dim lHeader As Long = CLng(BitConverter.ToInt32(abHeader, 0))

      

UPDATE: . According to my updated online test, when the JIT (Just-In-Time) compiler (thanks for reminding me @JamesThorpe!) Did its job, our methods are pretty much equally fast.



Link: http://ideone.com/lhJ61J

Bitwise Or              : 32767
Compile time            : 00:00:00.0000725
1M iterations avg.      : 00:00:00.0000003

Convert.ToInt64()       : <CAST ERROR>
Compile time            : ???

BitConverter.ToInt32()  : 32767
Compile time            : 00:00:00.0001834
1M iterations avg.      : 00:00:00.0000003

      

Now, if your application cannot handle a piece of code that takes 0.3 microseconds (0.0003 milliseconds) to execute, then I don't know what to tell you.;)

+3


source


The length of the Byte array needs to be 8 as size of long/int64 is 8

Dim abHeader(0 To 7) As Byte
Dim lHeader As Long = BitConvert.ToInt64(abHeader)

      

or with changed byte order:



Dim lHeader As Long = BitConvert.ToInt64(abHeader.Reverse())

      

0


source







All Articles