excel vba binary string to hexidecimal string

'Fast VBA function to convert binary string to hexadecimal string...

Function BinToHex$(bin$, Optional groupBy& = 1)
    Dim c&, i&, j&, hNdx&, nibble&, bits$, s$
    Dim b() As Byte, h() As Byte
    Static bHexChars() As Byte, pow2() As Byte
    
    Const HEX_CHARS$ = "0123456789ABCDEF"
    If (Not Not bHexChars) = 0 Then bHexChars = StrConv(HEX_CHARS, vbFromUnicode)
    If (Not Not pow2) = 0 Then pow2 = ChrW$(&H201) & ChrW$(&H804)

    b = StrConv(bin, vbFromUnicode)
    ReDim h(0 To -Int(-Len(bin) / 4) - 1)
    hNdx = UBound(h)
    
    For i = UBound(b) To 0 Step -1
        If b(i) = 49& Then nibble = nibble + pow2(c)
        c = c + 1
        If c = 4 Then
            h(hNdx) = bHexChars(nibble)
            hNdx = hNdx - 1
            nibble = 0
            c = 0
        End If
    Next
    If c Then h(hNdx) = bHexChars(nibble)
    BinToHex = StrConv(h, vbUnicode)
    
    If groupBy > 1 Then
        i = Len(BinToHex) + 1
        Do
            i = i - groupBy
            If i < 1 Then
                s = " " & Mid$(BinToHex, 1, i + groupBy - 1) & s
                Exit Do
            End If
            s = " " & Mid$(BinToHex, i, groupBy) & s
        Loop While i
        BinToHex = Trim$(s)
    End If
End Function

'-------------------------------------------------------------------------------

binaryStr = "11111100110101011110001101000110"

MsgBox BinToHex(binaryStr)      '<--displays: FCD5E346
MsgBox BinToHex(binaryStr, 4)   '<--displays: FCD5 E346
MsgBox BinToHex(binaryStr, 2)   '<--displays: FC D5 E3 46


'Note: this is an extremely fast and optimized function that can convert
'      an arbitrarily large binary string to hex.
'
'
'

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source