Re: Byte swapping efficiently

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



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
.



Relevant Pages

  • Byte swapping efficiently
    ... I'm working on an app that reads 16-bit signed integers in Motorola ... and needs to swap the two bytes into Intel ... Dim Result As String ...
    (microsoft.public.vb.general.discussion)
  • Search pattern
    ... Dim strfile As String ... Dim bAddressFound As Boolean ... Dim strCurrentChar As String ...
    (comp.databases.ms-access)
  • Auto Write Name and Merge across
    ... Dim Sheetname01 As String ... Dim WeekName01 As String ...
    (microsoft.public.excel.misc)
  • Re: multiplatform (pocketPC & desktopPC) (Daniel !!)
    ... Friend Versione As String ... Public Sub GetMyConnectionPalmare() ... Dim errorMessages As String ... Private Function GetDS_Desktop(ByVal SQL As String) As DataSet ...
    (microsoft.public.dotnet.framework.compactframework)
  • Re: multiplatform (pocketPC & desktopPC) (Daniel !!)
    ... Friend Versione As String ... Public Sub GetMyConnectionPalmare() ... Dim errorMessages As String ... Private Function GetDS_Desktop(ByVal SQL As String) As DataSet ...
    (microsoft.public.dotnet.framework.compactframework)