TIP: Click on subject to list as thread! ANSI
echo: visual_basic
to: All
from: `rick Rothstein` ricknos
date: 2005-02-10 18:57:00
subject: Re: How can I convert a Hex number to a binary number?

> Thanks Rick,
>  but i nee a little more info.  When I try to convert anything   like
$A ,
> it says undefined variable.
>
>             Hex2Bin (AF)
>
>  My numbers I need to display are single byte form such as  $OF, $AF.
Keep
> in mind  the dollar sign in only means that it is a hex number.
> I'm not familar with the proper way  for VB.  My hex numbers that are
> comming into the program will be a single byte in ASCII over MS Comm.
For
> instance I might receive a string  $FF $3B $CF without the dollar sign
.

The standard way to display hex values in VB is by preceding the hex
digits with "&h" or "&H". In any event, I have
modified the code to
permit hex values either with or without a leading "$" symbol.

' Limit on the size the HexString value is 2147483648 hex-digits
Function Hex2Bin(ByVal HexString As String, _
              Optional WithBlanks As Boolean) As Variant
    Dim X As Integer
    Const BinValues = "0000000100100011" & _
                      "0100010101100111" & _
                      "1000100110101011" & _
                      "1100110111101111"
    If Left$(HexString, 1) = "$" Then
      HexString = Mid$(HexString, 2)
    End If
    For X = 1 To Len(HexString)
        Hex2Bin = Hex2Bin & Mid$(BinValues, _
                  4 * Val("&h" & Mid$(HexString, X, 1)) + 1, 4)
        If WithBlanks Then Hex2Bin = Hex2Bin & " "
    Next
End Function

However, you need to pass arguments into the function as String data
types. That means, either put your values into a String variable and
pass that into the function

Dim HexValue As String
HexValue = "$AF"
MsgBox Hex2Bin(HexValue)

or, since the $ sign is optional,

Dim HexValue As String
HexValue = "AF"
MsgBox Hex2Bin(HexValue)

or, if you are passing in hex constants, surround them with quote marks

MsgBox Hex2Bin("$AF")

or

MsgBox Hex2Bin("AF")

Rick - MVP



--- UseNet To RIME Gateway {at} 2/10/05 6:47:33 PM ---
* Origin: MoonDog BBS, Brooklyn,NY, 718 692-2498, 1:278/230 (1:278/230)
SEEN-BY: 633/267 270 5030/786
@PATH: 278/230 10/345 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.