Results 1 to 3 of 3

Thread: Convert a binary file to hex code

  1. #1

    Thread Starter
    New Member
    Join Date
    Aug 2024
    Posts
    8

    Post Convert a binary file to hex code

    Basically, how do you convert a binary file to its hex code in VB.NET just like this (VB6) thread on this forum: https://www.vbforums.com/showthread....t=binary%20hex

    So what I need is:

    1. Read a binary file.

    2. Convert each byte of the file to its ASCII value. Note that since it is a binary file, there are going to be a lot of non-printable characters in there. So A becomes 65, backspace char becomes 8 etc.

    3. Convert this array of ASCII values to the array of their 2 digit HEX conversions so that 65 becomes 41 and 8 becomes 08 etc.

    4. Convert this array to a string.

    5. Convert this whole string back to the original binary file. (Another function for this, obviously)

    Right now I have:

    Code:
    Dim scr_filename As String = My.Computer.FileSystem.SpecialDirectories.Desktop + "\mypic.jpg"
    
    Dim fdata = My.Computer.FileSystem.ReadAllBytes(scr_filename)
    
                Dim res As String = "", fstr As String, num As Integer
                'res = System.Text.Encoding.ASCII.GetBytes(fdata)
    
                fstr = System.Text.Encoding.Default.GetString(fdata)
    
                For i As Integer = 0 To (fstr.Length - 1)
                    num = Asc(fstr.Substring(i, 1))
                    res += num.ToString + " "
                Next
                MsgBox(res)
    Running this unholy, wicked code for a 2 kb file generates the result within one second. For a 20 kb file, it takes around 4 seconds. For a 120 kb file ... well, I executed the code and went away from the computer for more than half an hour. When I returned, the messagebox had still not appeared and the form was stuck/disabled.

    How do I exorcise this code, or, perhaps sacrifice it at the alter of Elder VB.NET and get a whole fresh code to do my bidding?
    Last edited by Asheekay; Aug 26th, 2024 at 07:46 AM. Reason: Updated the code

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,370

    Re: Convert a binary file to hex code

    To read a binary file, use the IO.BinaryReader class: documentation

    To convert each by to its respective ASCII value, use the Text.ASCIIEncoding.GetString method: documentation

    To convert the bytes to their 2 digit hex value, you do not need to first convert them to their respective ASCII values, just convert the byte directly by calling ToString and passing the "X2" format: documentation

    To convert the collection to a String, use String.Concat: documentation

    To convert the 2 digit hex values back to their respective Byte values, you'd call Convert.ToByte: documentation

    After reading the relevant documentation and working something up, if you still have any issues feel free to reach back here with what you tried and what's going wrong.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  3. #3
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Convert a binary file to hex code

    Code:
        Public Iterator Function ReadBin(ByVal fileName As String) As IEnumerable(Of String)
            Using fs As FileStream = File.OpenRead(fileName)
                Using br As New BinaryReader(fs)
                    Do Until fs.Position = fs.Length
                        Yield br.ReadByte().ToString("X2").PadLeft(2, "0"c)
                    Loop
                End Using
            End Using
        End Function
    
    You can do it with the above function.

    Example of its use:-
    Code:
    Debug.WriteLine(String.Join(" ", ReadBin("d:\ax.txt")))
    Note that I wrote it as an iterator function for efficiency. This way you don't have to load the whole thing into memory and then process it byte by byte. You just have to iterate the object returned by the function and it will process it as you iterate it.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

Tags for this Thread

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