CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: HEX <-> BIN

  1. #1
    Join Date
    Mar 2001
    Location
    Germany
    Posts
    16

    HEX <-> BIN

    Hi,

    how can I in Visual Basic convert a number from it's Hex value into the binary value
    and vice versa?


    Thanks and Bye
    Sascha



  2. #2
    Join Date
    May 2000
    Location
    New York, NY, USA
    Posts
    2,878

    Re: HEX <-> BIN

    I don't know if you can do it directly, but here the code to convert Hex to decimal and then decimal to binary

    Hex to Dec
    Function HexToDec(HexValue As String) As Long
    HexToDec = Val("&H" & HexValue)
    End Function


    Function HexToDec(HexValue As String, Optional ToInteger As Boolean) As Long
    If ToInteger Then
    ' convert to an integer value, if possible.
    ' Use CInt() if you want to *always* convert to an Integer
    HexToDec = Val("&H" & HexValue)
    Else
    ' always convert to a Long. You can also use the CLng() function.
    HexToDec = Val("&H" & HexValue & "&")
    End If
    End Function

    Here's a function that will convert any decimal number less than 256 to binary:

    Function Decimal2Binary(TheNumber As Integer) As String
    Dim TheBinaryNumber As String
    Dim ThePosition As Integer
    Dim iWork As Integer
    TheBinaryNumber = "00000000"
    If TheNumber &lt; 256 Then
    ThePosition = 128
    For iWork = 1 To 8
    If TheNumber &gt;= ThePosition Then
    Mid$(TheBinaryNumber, iWork, 1) = "1"
    TheNumber = TheNumber - ThePosition
    End If
    ThePosition = ThePosition / 2
    Next
    End If
    Decimal2Binary = TheBinaryNumber
    End Function



    Iouri Boutchkine
    [email protected]
    Iouri Boutchkine
    [email protected]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured