Results 1 to 14 of 14

Thread: Reading file as HEX

  1. #1

    Thread Starter
    Frenzied Member vbNeo's Avatar
    Join Date
    May 2002
    Location
    Jutland, Denmark
    Posts
    1,994

    Reading file as HEX

    How do I read a file and get it's HEX values? Is it possible to get this in a string?

    Cheers!
    "Lies, sanctions, and cruise missiles have never created a free and just society. Only everyday people can do that."
    - Zack de la Rocha


    Hear me roar.

  2. #2
    Lively Member ranma_at's Avatar
    Join Date
    Oct 2002
    Location
    @ Home
    Posts
    72
    I m not sure what you re after, if you just need to convert text into string that `s easy.

    VB Code:
    1. Option Explicit  
    2.  
    3. Private m_InitHex as Boolean  
    4. Private m_ByteToHex(0 To 255, 0 To 1) as Byte  
    5. Private m_HexToByte(48 To 70, 48 To 70) as Byte  
    6.  
    7. Private Declare Sub FillMemory Lib "kernel32.dll" Alias "RtlFillMemory" (Destination as Any, ByVal Length as Long, ByVal Fill as Byte)  
    8.  
    9. Function HexToStr(HexText as String, Optional ByVal Separators as Long = 1) as String  
    10.  
    11.   Dim a as Long  
    12.   Dim Pos as Long  
    13.   Dim PosAdd as Long  
    14.   Dim ByteSize as Long  
    15.   Dim HexByte() as Byte  
    16.   Dim ByteArray() as Byte  
    17.  
    18.   'Initialize the hex routine
    19.   If (Not m_InitHex) Then Call InitHex  
    20.  
    21.   'The destination string is half
    22.   'the size of the source string
    23.   'when the separators are removed
    24.   If (Len(HexText) = 2) Then  
    25.     ByteSize = 1  
    26.   Else  
    27.     ByteSize = ((Len(HexText) + 1) \ (2 + Separators))  
    28.   End If  
    29.   ReDim ByteArray(0 To ByteSize - 1)  
    30.  
    31.   'Convert every HEX code to the
    32.   'equivalent ASCII character
    33.   PosAdd = 2 + Separators  
    34.   HexByte() = StrConv(HexText, vbFromUnicode)  
    35.   For a = 0 To (ByteSize - 1)  
    36.     ByteArray(a) = m_HexToByte(HexByte(Pos), HexByte(Pos + 1))  
    37.     Pos = Pos + PosAdd  
    38.   Next  
    39.  
    40.   'Now finally convert the byte
    41.   'array to the return string
    42.   HexToStr = StrConv(ByteArray, vbUnicode)  
    43.  
    44. End Function  
    45. Private Sub InitHex()  
    46.  
    47.   Dim a as Long  
    48.   Dim b as Long  
    49.   Dim HexBytes() as Byte  
    50.   Dim HexString as String  
    51.  
    52.   'The routine is initialized
    53.   m_InitHex = True  
    54.  
    55.   'Create a string with all hex values
    56.   HexString = String$(512, "0")  
    57.   For a = 1 To 255  
    58.     Mid$(HexString, 1 + a * 2 + -(a < 16)) = Hex(a)  
    59.   Next  
    60.   HexBytes = StrConv(HexString, vbFromUnicode)  
    61.  
    62.   'Create the Str->Hex array
    63.   For a = 0 To 255  
    64.     m_ByteToHex(a, 0) = HexBytes(a * 2)  
    65.     m_ByteToHex(a, 1) = HexBytes(a * 2 + 1)  
    66.   Next  
    67.  
    68.   'Create the Str->Hex array
    69.   For a = 0 To 255  
    70.     m_HexToByte(m_ByteToHex(a, 0), m_ByteToHex(a, 1)) = a  
    71.   Next  
    72.  
    73. End Sub  
    74. Function StrToHex(text as String, Optional Separator as String = " ") as String  
    75.  
    76.   Dim a as Long  
    77.   Dim Pos as Long  
    78.   Dim Char as Byte  
    79.   Dim PosAdd as Long  
    80.   Dim ByteSize as Long  
    81.   Dim ByteArray() as Byte  
    82.   Dim ByteReturn() as Byte  
    83.   Dim SeparatorLen as Long  
    84.   Dim SeparatorChar as Byte  
    85.  
    86.   'Initialize the hex routine
    87.   If (Not m_InitHex) Then Call InitHex  
    88.  
    89.   'Initialize variables
    90.   SeparatorLen = Len(Separator)  
    91.  
    92.   'Create the destination bytearray, this
    93.   'will be converted to a string later
    94.   ByteSize = (Len(text) * 2 + (Len(text) - 1) * SeparatorLen)  
    95.   ReDim ByteReturn(ByteSize - 1)  
    96.   Call FillMemory(ByteReturn(0), ByteSize, Asc(Separator))  
    97.  
    98.   'We convert the source string into a
    99.   'byte array to speed this up a tad
    100.   ByteArray() = StrConv(text, vbFromUnicode)  
    101.  
    102.   'Now convert every character to
    103.   'it's equivalent HEX code
    104.   PosAdd = 2 + SeparatorLen  
    105.   For a = 0 To (Len(text) - 1)  
    106.     ByteReturn(Pos) = m_ByteToHex(ByteArray(a), 0)  
    107.     ByteReturn(Pos + 1) = m_ByteToHex(ByteArray(a), 1)  
    108.     Pos = Pos + PosAdd  
    109.   Next  
    110.  
    111.   'Convert the bytearray to a string
    112.   StrToHex = StrConv(ByteReturn(), vbUnicode)  
    113.  
    114. End Function
    Things are not happening to you, things are happening because of you!

  3. #3
    PowerPoster
    Join Date
    Aug 2001
    Location
    new jersey
    Posts
    2,904
    it's not clear what it is you want to do, but I'd suggest you check out the "binary" option in the open statement

  4. #4

    Thread Starter
    Frenzied Member vbNeo's Avatar
    Join Date
    May 2002
    Location
    Jutland, Denmark
    Posts
    1,994

    Well

    What I need to do is extract a hex digit from a file(00 00 00 11), this digit changes from file to file, I do however have the address, which is 14(00 00 00 E0), so my idea was to convert it to a string, then parse it trhough... But I really can't get it to work - is there another, better way to do it ?
    "Lies, sanctions, and cruise missiles have never created a free and just society. Only everyday people can do that."
    - Zack de la Rocha


    Hear me roar.

  5. #5
    Elite Hacker Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,349
    'This is a little dangerous cause this is one good step
    'away to attatching a virus to the files.

    Option Explicit

    Dim Byte_Array() as Byte

    Private Sub File_Disassemble(File_Path As String, Get_Bytes() As Byte)



    'Tear apart the file by the byte!!!

    Dim Current_Line As Long

    Open File_Path For Binary Access Read As #1

    While Not EOF(1)

    ReDim Preserve Get_Bytes(Current_Line) As Byte

    Get #1, , Get_Bytes(Current_Line)

    Current_Line = Current_Line + 1

    Wend

    Close #1

    End Sub

    Private Sub File_Reassemble(File_Path As String, Set_Bytes() As Byte)

    'Puts the file back together.
    'Works on all file extentions, including exes!

    Dim Current_Line As Long

    Dim Byte_String As String

    Open File_Path For Output As #1

    For Current_Line = 0 To UBound(Set_Bytes) - 1

    Byte_String = Byte_String & Chr(Set_Bytes(Current_Line))

    Next Current_Line

    Print #1, Byte_String

    Close #1

    End Sub

  6. #6
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654
    VB Code:
    1. 'in a module
    2. Public Function GetByteFromFile(ByVal Filename As String, ByVal FilePosition As Long) As Byte
    3.     Dim FileNumber As Byte, Temp As Byte
    4.     FileNumber = FreeFile
    5.     On Error Goto ErrorHandler
    6.     Open Filename For Binary Access Read As #FileNumber
    7.         Seek #FileNumber, FilePosition
    8.         Get #FileNumber, , Temp
    9.     Close #FileNumber
    10.     GetByteFromFile = Temp
    11. ErrorHandler:
    12. End Function

    Then you can use Hex$() to convert it to a hex. Also, I posted this code yesterday, it reads all the data in a file and shows it as hex (separated by spaces):

    VB Code:
    1. 'in a module
    2. Public Function OpenFileAsHex(ByVal Filename As String) As String
    3.     Dim ReadBuffer() As Byte, ReturnBuffer() As Byte
    4.     Dim FileNumber As Byte, A As Long, B As Long
    5.     FileNumber = FreeFile
    6.     'open file
    7.     Open Filename For Binary Access Read As #FileNumber
    8.         'prepare a read buffer
    9.         ReDim Preserve ReadBuffer(LOF(FileNumber) - 1)
    10.         'prepare a return buffer
    11.         ReDim Preserve ReturnBuffer(LOF(FileNumber) * 3 - 1)
    12.         'read all data
    13.         Get #FileNumber, , ReadBuffer
    14.     Close #FileNumber
    15.     'convert numbers to 0 - F
    16.     For A = 0 To UBound(ReturnBuffer) Step 3
    17.         'divide by three (\ is faster than /)
    18.         B = A \ 3
    19.         '&H30 = 48, which is the character code for 0
    20.         'the code before it rips the four upper bits (value will be 0 - 15)
    21.         ReturnBuffer(A) = ((ReadBuffer(B) And &HF0) \ &H10) Or &H30
    22.         'rip the four lower bits and and add 48
    23.         ReturnBuffer(A + 1) = (ReadBuffer(B) And &HF) Or &H30
    24.         'space character to divide the hex values from each other
    25.         ReturnBuffer(A + 2) = &H20
    26.         'then check if character code is bigger than the code for number 9
    27.         'and add seven if it is so 10 will be A and 11 B and so on
    28.         If ReturnBuffer(A) > 57 Then ReturnBuffer(A) = ReturnBuffer(A) + 7
    29.         If ReturnBuffer(A + 1) > 57 Then ReturnBuffer(A + 1) = ReturnBuffer(A + 1) + 7
    30.     Next A
    31.     'convert to string
    32.     OpenFileAsHex = StrConv(ReturnBuffer, vbUnicode)
    33. End Function

    Usage:

    Text1.Text = OpenFileAsHex("c:\autoexec.bat")


    If you want to get a specific hex from the string, you can look it with logic Mid$(Text1.Text, Position * 3, 2). The code is rather fast once you compile it

  7. #7
    Member Siu Yan's Avatar
    Join Date
    Apr 2004
    Location
    Hong Kong --> Ireland
    Posts
    49
    I've asked a similar question a few days ago.

    Take a look at

    http://www.vbforums.com/showthread.p...ght=binary+hex

    My one is to read a binary file and change into Hex code.

    HTP
    Quitters never Win, Winners never Quit, But those who Never Win and Never Quit are Idiots

  8. #8
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654
    Heh, I replied the same topic and the code I have above is much faster

  9. #9
    Hyperactive Member
    Join Date
    Mar 2006
    Posts
    282

    Re: Reading file as HEX

    Quote Originally Posted by Merri
    VB Code:
    1. 'in a module
    2. Public Function GetByteFromFile(ByVal Filename As String, ByVal FilePosition As Long) As Byte
    3.     Dim FileNumber As Byte, Temp As Byte
    4.     FileNumber = FreeFile
    5.     On Error Goto ErrorHandler
    6.     Open Filename For Binary Access Read As #FileNumber
    7.         Seek #FileNumber, FilePosition
    8.         Get #FileNumber, , Temp
    9.     Close #FileNumber
    10.     GetByteFromFile = Temp
    11. ErrorHandler:
    12. End Function

    Then you can use Hex$() to convert it to a hex. Also, I posted this code yesterday, it reads all the data in a file and shows it as hex (separated by spaces):

    VB Code:
    1. 'in a module
    2. Public Function OpenFileAsHex(ByVal Filename As String) As String
    3.     Dim ReadBuffer() As Byte, ReturnBuffer() As Byte
    4.     Dim FileNumber As Byte, A As Long, B As Long
    5.     FileNumber = FreeFile
    6.     'open file
    7.     Open Filename For Binary Access Read As #FileNumber
    8.         'prepare a read buffer
    9.         ReDim Preserve ReadBuffer(LOF(FileNumber) - 1)
    10.         'prepare a return buffer
    11.         ReDim Preserve ReturnBuffer(LOF(FileNumber) * 3 - 1)
    12.         'read all data
    13.         Get #FileNumber, , ReadBuffer
    14.     Close #FileNumber
    15.     'convert numbers to 0 - F
    16.     For A = 0 To UBound(ReturnBuffer) Step 3
    17.         'divide by three (\ is faster than /)
    18.         B = A \ 3
    19.         '&H30 = 48, which is the character code for 0
    20.         'the code before it rips the four upper bits (value will be 0 - 15)
    21.         ReturnBuffer(A) = ((ReadBuffer(B) And &HF0) \ &H10) Or &H30
    22.         'rip the four lower bits and and add 48
    23.         ReturnBuffer(A + 1) = (ReadBuffer(B) And &HF) Or &H30
    24.         'space character to divide the hex values from each other
    25.         ReturnBuffer(A + 2) = &H20
    26.         'then check if character code is bigger than the code for number 9
    27.         'and add seven if it is so 10 will be A and 11 B and so on
    28.         If ReturnBuffer(A) > 57 Then ReturnBuffer(A) = ReturnBuffer(A) + 7
    29.         If ReturnBuffer(A + 1) > 57 Then ReturnBuffer(A + 1) = ReturnBuffer(A + 1) + 7
    30.     Next A
    31.     'convert to string
    32.     OpenFileAsHex = StrConv(ReturnBuffer, vbUnicode)
    33. End Function

    Usage:

    Text1.Text = OpenFileAsHex("c:\autoexec.bat")


    If you want to get a specific hex from the string, you can look it with logic Mid$(Text1.Text, Position * 3, 2). The code is rather fast once you compile it

    Great code
    But, can U make it afther load hex file in text box, save it again to binary ???

    Usage:

    Text1.Text = SaveFileAsBinary("c:\autoexec.bat")

    B.R
    VB Client/Server

  10. #10
    Banned randem's Avatar
    Join Date
    Oct 2002
    Location
    Maui, Hawaii
    Posts
    11,385

    Re: Reading file as HEX

    It seems no one knows about conversions anymore. It's a shame it's not taught anymore...


    All files are binary. Hex, Oct, ASCII and EBCIDIC are just different ways to display it and for a processor to operate on it.

  11. #11
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Reading file as HEX

    It seems people don't know too well about variable datatypes either or how character sets work and so on. Pretty important stuff for any programmer to know, really, otherwise it is just playing around with some code and saying "you can't do that!" or "I can't do that!" without knowing what the final compiled code actually does.

    In the end thing are pretty simple, but understanding how you can handle it is a bit more difficult.


    Anyways, my tip is: if you want to handle something, store it in memory in the most basic form it can be. Only change it to something else (ie. hex string) if you want to display it to the user. And only do it when you display it, and you don't need to convert everything at once. Also, when user inputs something, convert it internally into the most basic form. Think as if you have information layers:
    • Visual layer: information the user sees
    • Visual <-> data layer: interaction (conversions) between internal data and what the user sees
    • Data layer: the actual data in a format that is easy and fast for a computer to handle
    • Data <-> file layer: interaction (conversions) between internal data and a file format being used
    • File layer: the final file that contains the data (be it encrypted, compressed or as-is and whatever it actually contains)


    This is how all professional programs are done. To my eye it seems some programmers try to read a file and then try to handle it "directly", without making it easy to handle for a computer. If it isn't easy to handle for a computer, how can a programmer handle it any better? And the same for visual data: what is on a window isn't necessary easy to handle internally, even if it is easy for a user to handle.

    The big five: USER <-CONVERSION-> COMPUTER <-CONVERSION-> STORAGE


    Kind of a rant I guess, but maybe atleast one person finds this useful

  12. #12
    Hyperactive Member
    Join Date
    Mar 2006
    Posts
    282

    Re: Reading file as HEX

    I agree with U Merri,
    but I dont know how to load few kb of binary data in internal memory, goto
    xx address, erase 12 bytes, put new 12 bytes and save file again as binary.
    Since I can only see where are thouse 12 bytes (24 HEX) and also copy another (24 HEX), when I convert it to HEX.
    I would be very greatfull if U show me how this can be done using only
    few lines of code.

    I have attach here 2kb binary file

    please convert txt to bin

    here is that file open with hex editor, already marked bytes need to be changed:

    selected binary/hex data must be changed wit this data:

    938690B56A43787384ADFCAF

    Please help me solve this problem !

    VB Code:
    1. Public Function GetByteFromFile(ByVal Filename As String, ByVal FilePosition As Long) As Byte
    2.     Dim FileNumber As Byte, Temp As Byte
    3.     FileNumber = FreeFile
    4.     On Error GoTo ErrorHandler
    5.     Open Filename For Binary Access Read As #FileNumber
    6.         Seek #FileNumber, FilePosition
    7.         Get #FileNumber, , Temp
    8.     Close #FileNumber
    9.     GetByteFromFile = Temp
    10. ErrorHandler:
    11. End Function
    12. Public Function OpenFileAsHex(ByVal Filename As String) As String
    13.     Dim ReadBuffer() As Byte, ReturnBuffer() As Byte
    14.     Dim FileNumber As Byte, A As Long, B As Long
    15.     FileNumber = FreeFile
    16.     'open file
    17.     Open Filename For Binary Access Read As #FileNumber
    18.         'prepare a read buffer
    19.         ReDim Preserve ReadBuffer(LOF(FileNumber) - 1)
    20.         'prepare a return buffer
    21.         ReDim Preserve ReturnBuffer(LOF(FileNumber) * 3 - 1)
    22.         'read all data
    23.         Get #FileNumber, , ReadBuffer
    24.     Close #FileNumber
    25.     'convert numbers to 0 - F
    26.     For A = 0 To UBound(ReturnBuffer) Step 3
    27.         'divide by three (\ is faster than /)
    28.         B = A \ 3
    29.         '&H30 = 48, which is the character code for 0
    30.         'the code before it rips the four upper bits (value will be 0 - 15)
    31.         ReturnBuffer(A) = ((ReadBuffer(B) And &HF0) \ &H10) Or &H30
    32.         'rip the four lower bits and and add 48
    33.         ReturnBuffer(A + 1) = (ReadBuffer(B) And &HF) Or &H30
    34.         'space character to divide the hex values from each other
    35.         ReturnBuffer(A + 2) = &H20
    36.         'then check if character code is bigger than the code for number 9
    37.         'and add seven if it is so 10 will be A and 11 B and so on
    38.         If ReturnBuffer(A) > 57 Then ReturnBuffer(A) = ReturnBuffer(A) + 7
    39.         If ReturnBuffer(A + 1) > 57 Then ReturnBuffer(A + 1) = ReturnBuffer(A + 1) + 7
    40.     Next A
    41.     'convert to string
    42.     OpenFileAsHex = StrConv(ReturnBuffer, vbUnicode)
    43. End Function

    VB Code:
    1. Private Sub Form_Load()
    2. On Error GoTo error
    3. Text2.Text = OpenFileAsHex("c:\test.bin")
    4. Dim sStr$
    5. sStr = Text2.Text
    6. sStr = Replace(sStr, " ", "")
    7. Text2.Text = sStr
    8. Exit Sub
    9. error:
    10. MsgBox "**** happens! Restart aplication and try again ! "
    11. Exit Sub
    12. End Sub

    VB Code:
    1. Private Sub Text1_Change()
    2. On Error GoTo error
    3. Dim sStr$
    4. sStr = Text1.Text
    5. sStr = Replace(sStr, " ", "")
    6. Text1.Text = sStr
    7. Exit Sub
    8. error:
    9. MsgBox "**** happens! Restart aplication and try again ! "
    10. Exit Sub
    11. End Sub

    VB Code:
    1. Private Sub Command4_Click()
    2. Text2.SelStart = 10
    3.     Text2.SelLength = 6
    4.     Text2.SetFocus
    5.   '  pause 2000
    6.     'erasing selected text
    7.     Text2.SelText = ""
    8.     'copy text1 on place where is erased in text2
    9. End Sub

    so how to convert text2 to bin and save it to file?



    B.R
    VB Client/Server

    I have solve my problem...
    Last edited by VB Client/Server; Jun 18th, 2006 at 07:14 AM. Reason: Problem solved ...

  13. #13

    Thread Starter
    Frenzied Member vbNeo's Avatar
    Join Date
    May 2002
    Location
    Jutland, Denmark
    Posts
    1,994

    Re: Reading file as HEX

    Quote Originally Posted by Merri
    It seems people don't know too well about variable datatypes either or how character sets work and so on. Pretty important stuff for any programmer to know, really, otherwise it is just playing around with some code and saying "you can't do that!" or "I can't do that!" without knowing what the final compiled code actually does.
    You really shouldn't judge the entire programming community just based on the users here at VBF .

    I've learned a lot since I started using other languages than Visual Basic, and TBH, most of the people signed up at this forum are just like I was - I didn't have any idea about data types either, nor did I understand the principle of binary, and the way data is handled.

    However, since I changed to Java(and later, C#), I've read a few books explaining a lot more than any tutorial could've, plus - I've grown.

    So, it's true that most of the users here have no idea what a datatype actually is, or how data is handled by the computer - that doesn't mean they're dum, they just haven't found the right source of information yet.

    To sum up; don't judge the entire programming community based on you're observations here at VBF .

    Thanks for the replys! Although the question is somewhat obsolete as of 2004 .
    "Lies, sanctions, and cruise missiles have never created a free and just society. Only everyday people can do that."
    - Zack de la Rocha


    Hear me roar.

  14. #14
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Reading file as HEX

    Who said I talked about the entire programming community? That's quite a broad assumption But I won't go into this more than this; wrong thread, wrong forum.

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