Re: Byte swapping efficiently
- From: "Jim Mack" <jmack@xxxxxxxxxxxxxxx>
- Date: Tue, 2 May 2006 19:58:34 -0400
John Hatpin wrote:
Anyone good at low-level data manipulation?
I'm working on an app that reads 16-bit signed integers in Motorola
(MSB-first) format, and needs to swap the two bytes into Intel
(LSB-first) order and return them as a Single. Currently, it uses the
following function to do the job, and it seems to work okay:
Public Function ByteSwap(Value As Integer) As Single
Dim S As String
Dim Result As String
Dim I As Single
S = Hex$(Value)
S = String(4 - Len(S), "0") & S
For I = 3 To 1 Step -2
Result = Result & Mid(S, I, 2)
Next
ByteSwap = Val("&H" & Result)
End Function
Unfortunately, that gets called a helluva lot, and debugging indicates
that the function is a major bottleneck. Not surprising, with all
that string handling going on.
Two things strike me: (a) there must be a much more efficient way to
do the job, maybe in a single line of code, and (b) I haven't a clue
what it is.
Any ideas, anyone?
Are you saying that the 16 bits comprise a single, or that you want to return a single having the same value as the (byte-swapped) integer? I guess the latter, since a Single actually has 4 bytes, not 2. If you're using a single only to avoid overflowing a signed integer, you should definitely consider a long integer instead. Just eliminate the "CSng()" below to do that.
Temp& = CLng(Value) : If Temp < 0 Then Temp = Temp + 65536
bswp% = CSng(((Temp And &HFF00&) \ &H100) + ((Temp And &HFF) * &H100))
Check the parentheses there -- definitely air code.
--
Jim Mack
MicroDexterity Inc
www.microdexterity.com
.
- References:
- Byte swapping efficiently
- From: John Hatpin
- Byte swapping efficiently
- Prev by Date: Re: Throw Two Error in Same Procedure?
- Next by Date: Re: Using with
- Previous by thread: Re: Byte swapping efficiently
- Next by thread: Re: Byte swapping efficiently
- Index(es):
Relevant Pages
|