VbQuestionGuy
VbQuestionGuy

Reputation: 31

Reverse the order of Hex digits

I need to take an integer value and convert it so that when it is represented in hexadecimal, the digits are reversed. For instance:

Dim a As Integer = &H4321
Dim a_changedorder As Integer = ReverseHexDigits(a)
Console.Writeline(a_changedorder.ToString("X4")) ' Should output 1234

How can I implement a ReverseHexDigits method that works like that?

As a second example, &H4F2A should become &HA2F4.

Upvotes: 2

Views: 2577

Answers (2)

Steven Doggart
Steven Doggart

Reputation: 43743

While Matt's method will work, it is rather inefficient to convert the integer to a hexadecimal string, reverse the order of the characters in the string, and then parse it back into an integer again. If efficiency is important, and you only need to reverse the nibbles in a two-byte integer, then the following will work:

Public Function ReverseHexDigits(input As Integer) As Integer
    Return ((input And &HF) << 12) Or 
        ((input And &HF0) << 4) Or 
        ((input And &HF00) >> 4) Or 
        ((input And &HF000) >> 12)
End Function

However, that's confusing, since it only operates on the lower two-bytes. It would be more clear if it operated on UShort variables instead:

Public Function ReverseHexDigits(input As UShort) As UShort
    Return ((input And CUShort(&HF)) << 12) Or
        ((input And CUShort(&HF0)) << 4) Or
        ((input And CUShort(&HF00)) >> 4) Or
        ((input And CUShort(&HF000)) >> 12)
End Function

Upvotes: 4

Matt Wilko
Matt Wilko

Reputation: 27322

(I really can't understand why you would want to do this...but) Just convert the numeric value to a string, reverse it then convert back to a numeric value:

    Dim a As UShort = &H4321

    Dim hexCharArray As Char() = a.ToString("X4").ToCharArray
    Array.Reverse(hexCharArray)
    Dim hexStringReversed = New String(hexCharArray)

    Dim a_changedorder As UShort = Convert.ToUInt16(hexStringReversed, 16)

Confirm the output is correct:

Debug.WriteLine(a_changedorder.ToString("X4")) '1234

Note you should be using UShort as you have only two bytes, Integer is signed and is 4 bytes

Upvotes: 1

Related Questions