vb.netcastinghexvisual-studio-2022

Converting a binary file contents to their hex code string in VB.NET


So I am making an image obfuscator which will help save the privacy of my images on a shared computer. The idea is to read the contents of the image, convert the bytes array into their corresponding ANSI array, convert the ANSI (decimal) to hex and finally save that hex code array in a new file. Then I can simply delete the original file.

What I have come up with, so far, is this:

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

        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)

The issue with this code is that it takes about 10 seconds to convert a 20 kb file to ANSI and beyond 20 kb, it simply freezes and I never get any output at all. Please also note that so far this is only converting bytes into their ANSI values and not converting the ANSI into their corresponding hex code.

Is there any method to optimize this code so as to be able to convert up to 400-500 kb files? Many thanks.


Solution

  • The Asc function inside a loop can be slow when processing large amounts of data.

    You don't need to convert bytes to characters and then to ANSI values, just process the bytes directly.

    Dim scr_filename As String = My.Computer.FileSystem.SpecialDirectories.Desktop + "\mypic.jpg"
    
    Dim fileBytes As Byte() = File.ReadAllBytes(scr_filename)
    
    Dim hexString As String = String.Join("", fileBytes.Select(Function(b) b.ToString("X2")))
    
    File.WriteAllText("path_to_your_output_file.txt", hexString)