Encode / Decode Data to and from Hex

Submitted on: 1/24/2015 8:11:00 AM
By: Jason Allen (from psc cd)  
Level: Beginner
User Rating: By 4 Users
Compatibility: VB 5.0, VB 6.0, VBA MS Excel
Views: 355
     Learn how to take strings and encode them to a data file in HEX format, and how to pull strings from a HEX-encoded file and convert them back into readable text! Please Vote on this Tutorial! It doesn't format quite right in PSC, so I suggest downloading the htm version and viewing it that way.

This article has accompanying files
				Encoding & Decoding in HEX Tutorial

Please Vote on this Tutorial!

Ever wanted to create your own encoded program data? Can't figure out how to do it?
This tutorial shows you how to encode and decode your custom data file to a hex format and back again.

Encoding Data to Hex:

Thanks to feedback, I realized that the conversion from hex into dec is a lot easier than I made it before. I updated the tutorial to show the easier way.

'Declare our variables
'StringLength holds the length of the string that we are converting
Dim StringLength As Integer
'MyString holds the string that we are converting
Dim MyString As String
'MyChar holds the current character that we are converting
Dim MyChar As String
'myHex holds the hex version of the current character
Dim myHex As String
'ConvertedString holds the new string in HEX-encoded format

'MyString is whatever you want it to say
MyString = "This is a test string for data encoding"
'First, we take the string and get the length
StringLength = Len(MyString)

'Now, we loop through each character in the string to convert the string one character at a time.
'We have to convert the character first into the ASCII equivalent of the character,
'then convert the ascii value into hex.

'loop through each character of the string
For I = 1 To StringLength
    'get the next character from the string and set myChar to that character. Uses the
    'Mid$(String, Begin, Length) function.
    MyChar = Mid$(MyString, I, 1)
    'check to make sure myChar is not equal to nothing
    If MyChar <> "" Then
       'take the ascii number of the character and convert it to a hex number.
       'The ASC function returns the ASCII number (between 0 and 255) of the character.
       'The HEX function returns the hexadecimal value of the number passed to it
       '(in this case, the ASCII value of the character)
       myHex = Hex(Asc(MyChar))
       'Add the new HEX value to the end of the ConvertedString. We're also going to add a separator
       'to make it easier for us to decode later on. Since HEX goes 0-9 and A-E, we'll use the letter G
       'as a separator between hex values. You can use any letter you prefer, except for 0-9 and A-E
       ConvertedString = ConvertedString & myHex & "G"
    End If
Next I

'Your String is now converted. If you wanted to add another line to the string, for instance, if you are using this to convert a file to hex, just add
'"& VbCrLf" to then end of the Converted String Statement, then keep adding all the strings you want.
'Now, you can output the data to your data file. The great thing about this is that you can create any unused file extension you want. Use the Open
statement as follows:

'Replace Data.Enc with whatever filename you want, Use the "Open Filename For OpenType As FileNumber" Function
Open "Data.Enc" For Append As #1 'Or use For Output for new files
'Print your new ConvertedString to the File
Print #1, ConvertedString
'Reset the string for later use
ConvertedString = ""
'Close the File
Close #1

'You now have a new file that contains your string(s) in encoded hex format. Each line, if applicable, is separated by a Carriage Return.

'Decoding Data from Hex back to text:

'we 'll assume you used the above process and now have a file that contains your text in the encoded hex format.
'First, a few notes: because the character set is always from 0 - 255, we know the highest hex value of any character is FF (255 in dec). Second, we also know that you won't be using the first 16 (0-15) values of the character ASCII set, because they don't represent common text. So we can now correctly assume that the characters that we converted into HEX will ALWAYS be represented by two characters in HEX Format. For example, Spacebar is equal to ASCII 32, which is 20 in HEX. is equal to 255 in ASCII, which is FF in HEX. (note that that is a Y with double dots over it, not the regular Y, which is 89 in ASCII). So Knowing this, we can proceed knowing that every two entries in the encoded file make up one character in real text.

'HexString stores a line from the data file in hex format
Dim HexString As String
'OneChar stores one character at a time from the HexString
Dim OneChar As String
'TwoChar stores sets of two characters from the HexString - which equals one text character after conversion
Dim TwoChar As String
'NewText stores the newly converted to text character.
Dim NewText As String

'Open the encoded file for input, use the "Open Filename for Input as FileNumber" Function
Open "Data.Enc" For Input As #1

'Input lines from encoded file until we reach the end of file (EOF)
While Not EOF(1)
    'input a line
    Line Input #1, HexString
    'Loop through the string positions from 1 to the length of the string (using the LEN function again)
    For I = 1 To Len(HexString)
        'Pull One character at a time from the string, in order. NOTE: the reason we pull one character
        'at a time rather than two (since we know all text = two hex characters), is because we added in
        'the "fake" G, so we have to pull one at a time to make sure we don't pass the G and create errors.
        'If you don't use the added "G", you can modify this function to pull two characters at a time and
        'evaluate the string that way.
        'We again use the Mid function to pull data.
        OneChar = (Mid$(HexString, I, 1))
        'check to see if our "dummy character" of G is the letter we pulled. If it is, we know that TwoChar
        'has two hex values that we can now convert back to text.
        If OneChar = "G" Then
            'The function Val converts the hex string back into dec format
            '(which is equal to the text characters ASCII value).
            'We then use the Chr function to convert the ASCII value back to it's original text value,
            'and add it to the decoded string variable. Then we can reset our variables.
            NewText = Chr(Val("&H" + TwoChar))
            'Add to DecodedString
            DecodedString = DecodedString & NewText
            'reset OneChar and TwoChar
            OneChar = ""
            TwoChar = ""
            'If we didn't reach the dummy character (G), we know we need to pull another letter
            'from the string, and then add it to our TwoChar variable.
            TwoChar = TwoChar & OneChar
        End If
    Next I
    'Print the line where ever you want. In this example, I will open a new file and print it there.
    Open "Converted.dat" For Output As #2
    Print #1, DecodedString
    'Reset DecodedString for next Line
    DecodedString = ""

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
  3. Scan the source code with Minnow's Project Scanner

If you don't have a virus scanner, you can get one at many places on the net

Other 2 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.