|
-
Dec 3rd, 2003, 02:04 PM
#1
Thread Starter
Frenzied Member
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.
-
Dec 3rd, 2003, 02:15 PM
#2
Lively Member
I m not sure what you re after, if you just need to convert text into string that `s easy.
VB Code:
Option Explicit
Private m_InitHex as Boolean
Private m_ByteToHex(0 To 255, 0 To 1) as Byte
Private m_HexToByte(48 To 70, 48 To 70) as Byte
Private Declare Sub FillMemory Lib "kernel32.dll" Alias "RtlFillMemory" (Destination as Any, ByVal Length as Long, ByVal Fill as Byte)
Function HexToStr(HexText as String, Optional ByVal Separators as Long = 1) as String
Dim a as Long
Dim Pos as Long
Dim PosAdd as Long
Dim ByteSize as Long
Dim HexByte() as Byte
Dim ByteArray() as Byte
'Initialize the hex routine
If (Not m_InitHex) Then Call InitHex
'The destination string is half
'the size of the source string
'when the separators are removed
If (Len(HexText) = 2) Then
ByteSize = 1
Else
ByteSize = ((Len(HexText) + 1) \ (2 + Separators))
End If
ReDim ByteArray(0 To ByteSize - 1)
'Convert every HEX code to the
'equivalent ASCII character
PosAdd = 2 + Separators
HexByte() = StrConv(HexText, vbFromUnicode)
For a = 0 To (ByteSize - 1)
ByteArray(a) = m_HexToByte(HexByte(Pos), HexByte(Pos + 1))
Pos = Pos + PosAdd
Next
'Now finally convert the byte
'array to the return string
HexToStr = StrConv(ByteArray, vbUnicode)
End Function
Private Sub InitHex()
Dim a as Long
Dim b as Long
Dim HexBytes() as Byte
Dim HexString as String
'The routine is initialized
m_InitHex = True
'Create a string with all hex values
HexString = String$(512, "0")
For a = 1 To 255
Mid$(HexString, 1 + a * 2 + -(a < 16)) = Hex(a)
Next
HexBytes = StrConv(HexString, vbFromUnicode)
'Create the Str->Hex array
For a = 0 To 255
m_ByteToHex(a, 0) = HexBytes(a * 2)
m_ByteToHex(a, 1) = HexBytes(a * 2 + 1)
Next
'Create the Str->Hex array
For a = 0 To 255
m_HexToByte(m_ByteToHex(a, 0), m_ByteToHex(a, 1)) = a
Next
End Sub
Function StrToHex(text as String, Optional Separator as String = " ") as String
Dim a as Long
Dim Pos as Long
Dim Char as Byte
Dim PosAdd as Long
Dim ByteSize as Long
Dim ByteArray() as Byte
Dim ByteReturn() as Byte
Dim SeparatorLen as Long
Dim SeparatorChar as Byte
'Initialize the hex routine
If (Not m_InitHex) Then Call InitHex
'Initialize variables
SeparatorLen = Len(Separator)
'Create the destination bytearray, this
'will be converted to a string later
ByteSize = (Len(text) * 2 + (Len(text) - 1) * SeparatorLen)
ReDim ByteReturn(ByteSize - 1)
Call FillMemory(ByteReturn(0), ByteSize, Asc(Separator))
'We convert the source string into a
'byte array to speed this up a tad
ByteArray() = StrConv(text, vbFromUnicode)
'Now convert every character to
'it's equivalent HEX code
PosAdd = 2 + SeparatorLen
For a = 0 To (Len(text) - 1)
ByteReturn(Pos) = m_ByteToHex(ByteArray(a), 0)
ByteReturn(Pos + 1) = m_ByteToHex(ByteArray(a), 1)
Pos = Pos + PosAdd
Next
'Convert the bytearray to a string
StrToHex = StrConv(ByteReturn(), vbUnicode)
End Function
Things are not happening to you, things are happening because of you!
-
Dec 3rd, 2003, 02:16 PM
#3
PowerPoster
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
-
Dec 3rd, 2003, 03:07 PM
#4
Thread Starter
Frenzied Member
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.
-
Aug 5th, 2004, 10:16 PM
#5
'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
-
Aug 6th, 2004, 04:26 AM
#6
VB Code:
'in a module
Public Function GetByteFromFile(ByVal Filename As String, ByVal FilePosition As Long) As Byte
Dim FileNumber As Byte, Temp As Byte
FileNumber = FreeFile
On Error Goto ErrorHandler
Open Filename For Binary Access Read As #FileNumber
Seek #FileNumber, FilePosition
Get #FileNumber, , Temp
Close #FileNumber
GetByteFromFile = Temp
ErrorHandler:
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:
'in a module
Public Function OpenFileAsHex(ByVal Filename As String) As String
Dim ReadBuffer() As Byte, ReturnBuffer() As Byte
Dim FileNumber As Byte, A As Long, B As Long
FileNumber = FreeFile
'open file
Open Filename For Binary Access Read As #FileNumber
'prepare a read buffer
ReDim Preserve ReadBuffer(LOF(FileNumber) - 1)
'prepare a return buffer
ReDim Preserve ReturnBuffer(LOF(FileNumber) * 3 - 1)
'read all data
Get #FileNumber, , ReadBuffer
Close #FileNumber
'convert numbers to 0 - F
For A = 0 To UBound(ReturnBuffer) Step 3
'divide by three (\ is faster than /)
B = A \ 3
'&H30 = 48, which is the character code for 0
'the code before it rips the four upper bits (value will be 0 - 15)
ReturnBuffer(A) = ((ReadBuffer(B) And &HF0) \ &H10) Or &H30
'rip the four lower bits and and add 48
ReturnBuffer(A + 1) = (ReadBuffer(B) And &HF) Or &H30
'space character to divide the hex values from each other
ReturnBuffer(A + 2) = &H20
'then check if character code is bigger than the code for number 9
'and add seven if it is so 10 will be A and 11 B and so on
If ReturnBuffer(A) > 57 Then ReturnBuffer(A) = ReturnBuffer(A) + 7
If ReturnBuffer(A + 1) > 57 Then ReturnBuffer(A + 1) = ReturnBuffer(A + 1) + 7
Next A
'convert to string
OpenFileAsHex = StrConv(ReturnBuffer, vbUnicode)
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
-
Aug 6th, 2004, 04:45 AM
#7
Member
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 
-
Aug 6th, 2004, 05:47 AM
#8
Heh, I replied the same topic and the code I have above is much faster
-
Jun 15th, 2006, 07:54 PM
#9
Hyperactive Member
Re: Reading file as HEX
 Originally Posted by Merri
VB Code:
'in a module
Public Function GetByteFromFile(ByVal Filename As String, ByVal FilePosition As Long) As Byte
Dim FileNumber As Byte, Temp As Byte
FileNumber = FreeFile
On Error Goto ErrorHandler
Open Filename For Binary Access Read As #FileNumber
Seek #FileNumber, FilePosition
Get #FileNumber, , Temp
Close #FileNumber
GetByteFromFile = Temp
ErrorHandler:
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:
'in a module
Public Function OpenFileAsHex(ByVal Filename As String) As String
Dim ReadBuffer() As Byte, ReturnBuffer() As Byte
Dim FileNumber As Byte, A As Long, B As Long
FileNumber = FreeFile
'open file
Open Filename For Binary Access Read As #FileNumber
'prepare a read buffer
ReDim Preserve ReadBuffer(LOF(FileNumber) - 1)
'prepare a return buffer
ReDim Preserve ReturnBuffer(LOF(FileNumber) * 3 - 1)
'read all data
Get #FileNumber, , ReadBuffer
Close #FileNumber
'convert numbers to 0 - F
For A = 0 To UBound(ReturnBuffer) Step 3
'divide by three (\ is faster than /)
B = A \ 3
'&H30 = 48, which is the character code for 0
'the code before it rips the four upper bits (value will be 0 - 15)
ReturnBuffer(A) = ((ReadBuffer(B) And &HF0) \ &H10) Or &H30
'rip the four lower bits and and add 48
ReturnBuffer(A + 1) = (ReadBuffer(B) And &HF) Or &H30
'space character to divide the hex values from each other
ReturnBuffer(A + 2) = &H20
'then check if character code is bigger than the code for number 9
'and add seven if it is so 10 will be A and 11 B and so on
If ReturnBuffer(A) > 57 Then ReturnBuffer(A) = ReturnBuffer(A) + 7
If ReturnBuffer(A + 1) > 57 Then ReturnBuffer(A + 1) = ReturnBuffer(A + 1) + 7
Next A
'convert to string
OpenFileAsHex = StrConv(ReturnBuffer, vbUnicode)
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
-
Jun 15th, 2006, 08:53 PM
#10
-
Jun 16th, 2006, 02:25 AM
#11
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
-
Jun 16th, 2006, 04:33 AM
#12
Hyperactive Member
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:
Public Function GetByteFromFile(ByVal Filename As String, ByVal FilePosition As Long) As Byte
Dim FileNumber As Byte, Temp As Byte
FileNumber = FreeFile
On Error GoTo ErrorHandler
Open Filename For Binary Access Read As #FileNumber
Seek #FileNumber, FilePosition
Get #FileNumber, , Temp
Close #FileNumber
GetByteFromFile = Temp
ErrorHandler:
End Function
Public Function OpenFileAsHex(ByVal Filename As String) As String
Dim ReadBuffer() As Byte, ReturnBuffer() As Byte
Dim FileNumber As Byte, A As Long, B As Long
FileNumber = FreeFile
'open file
Open Filename For Binary Access Read As #FileNumber
'prepare a read buffer
ReDim Preserve ReadBuffer(LOF(FileNumber) - 1)
'prepare a return buffer
ReDim Preserve ReturnBuffer(LOF(FileNumber) * 3 - 1)
'read all data
Get #FileNumber, , ReadBuffer
Close #FileNumber
'convert numbers to 0 - F
For A = 0 To UBound(ReturnBuffer) Step 3
'divide by three (\ is faster than /)
B = A \ 3
'&H30 = 48, which is the character code for 0
'the code before it rips the four upper bits (value will be 0 - 15)
ReturnBuffer(A) = ((ReadBuffer(B) And &HF0) \ &H10) Or &H30
'rip the four lower bits and and add 48
ReturnBuffer(A + 1) = (ReadBuffer(B) And &HF) Or &H30
'space character to divide the hex values from each other
ReturnBuffer(A + 2) = &H20
'then check if character code is bigger than the code for number 9
'and add seven if it is so 10 will be A and 11 B and so on
If ReturnBuffer(A) > 57 Then ReturnBuffer(A) = ReturnBuffer(A) + 7
If ReturnBuffer(A + 1) > 57 Then ReturnBuffer(A + 1) = ReturnBuffer(A + 1) + 7
Next A
'convert to string
OpenFileAsHex = StrConv(ReturnBuffer, vbUnicode)
End Function
VB Code:
Private Sub Form_Load()
On Error GoTo error
Text2.Text = OpenFileAsHex("c:\test.bin")
Dim sStr$
sStr = Text2.Text
sStr = Replace(sStr, " ", "")
Text2.Text = sStr
Exit Sub
error:
MsgBox "**** happens! Restart aplication and try again ! "
Exit Sub
End Sub
VB Code:
Private Sub Text1_Change()
On Error GoTo error
Dim sStr$
sStr = Text1.Text
sStr = Replace(sStr, " ", "")
Text1.Text = sStr
Exit Sub
error:
MsgBox "**** happens! Restart aplication and try again ! "
Exit Sub
End Sub
VB Code:
Private Sub Command4_Click()
Text2.SelStart = 10
Text2.SelLength = 6
Text2.SetFocus
' pause 2000
'erasing selected text
Text2.SelText = ""
'copy text1 on place where is erased in text2
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 ...
-
Jun 18th, 2006, 07:10 AM
#13
Thread Starter
Frenzied Member
Re: Reading file as HEX
 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.
-
Jun 18th, 2006, 10:01 AM
#14
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|