#๐Ÿ”’ How to read a file as binary or hex "string" so that I can do regex search?

12 messages ยท Page 1 of 1 (latest)

kind portal
#

For example,
If I open a file using hex editor, it showed
3C 47 23 56 59 59 66 38 38 5C 67 3A 5A 70 29 32 47 25 28 63 5D 33 32 39 69 30 58 53 2B 4B 44 61 45 27 7A 3F 21 64 76 5B 54 5D 28 46 75 7A 52 5F

How can I get it as "string"?

Should I do below?

hfile1 = open("example1.txt", "rb")
bfile1 = hfile1.read()

But if I use my code above, then I search regex using my code below:

afile1 = re.findall('[0-9A-Fa-f]{2}', bfile1)

There will be error:
TypeError: cannot use a string pattern on a bytes-like object

Then If I modify my regex search using below:

afile1 = re.findall(b'[0-9A-Fa-f]{2}', bfile1)

The regex search result will do regex to String part (Decoded Text) of hex editor:
<G#VYYf88\g:Zp)2G%(c]329i0XS+KDaE'z?!dv[T](FuzR_

So the result is not as I expected

Thank You

molten abyssBOT
#

@kind portal

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

uncut shuttle
#

reading from a binary file gives you a bytes object, if you want to turn a bytes object into a hex string then you can use your_bytes_object.hex()

#

when used on the bytes b"\x01\x02\x0A" it returns the hex string "01020a"

#

keep in mind that maybe you want the hex string in a different letter case (A instead of a) or maybe you want spaces between each byte, to do this you can use str.upper and .hex(" ")

earnest stirrup
#

if i were you i'd store the hex in memory as a string so i can run string operations on it, it'd be much easier

kind portal
#

@uncut shuttle
Thank You
Helpful

@earnest stirrup
How to do that?

halcyon iris
#

variable

#

if you want a hex representation of your file, use .hex and .upper if you need to. then you can search that with regex for some patterns

#

if you do a regex search on the bytes of a file, those bytes won't be interpreted as hex. they'll just be searched as is

molten abyssBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.