1

I have a file named k_hex which contains the below data. I read the data from file by using below command, and I want to save the data into a list.

hex_data = open('k_hex','r').read()
print hex_data
@0
45
4C
4C
41
00
07
00
00
10

I want my data in below format. How can I get it, I'm new to Python.

hex_data = [0x@0, 0x45, 0x4C, 0x4C, 0X41, 0x00, 0x07, 0x00, 0x00, 0x10]

Can you anyone please do let me know how to achieve the 2nd part?

Thanks.

4
  • If you read the file line at at time, you will make your life easier. As for the 2nd part, a whole number is going to display as an integer, unless you convert it to a hex string, so you'll get a list like ... '0x10']. Is that ok? (If not, why do you want a "format" in hex?) Commented Aug 30, 2018 at 15:36
  • @doctorlove i want something like this [0x11, 0x22, 0x33] , i dont want those quotes. Any way please . I need it in hex format because i need to write data into my vip memory in bytes . Commented Aug 30, 2018 at 15:56
  • You probably want them as bytes in that case. Not "numbers". Commented Aug 30, 2018 at 16:00
  • @doctorlove can you let me know for bytes Commented Aug 30, 2018 at 17:50

1 Answer 1

2
hex_data = ["0x" + hh for hh in hex_data.split()]

hex_data.split() splits your file into the list of pairs of hexadecimal symbols, and "0x" + hh will give the Ox characters in front of them.

Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to remove those single quotes ...... ['0x@0', '0x45', '0x4C', '0x4C', '0x41', '0x00', '0x07', '0x00', '0x00', '0x10', '0x06', '0x6E', '0x00', '0x01', '0x00', '0xE4', '0x05']
Those single quotes are only Python syntax for strings - they are neither part of the string itself (e.g. in the memory or on the disk file), nor of the output of the print() function. You may convert them to integers with the int() function with the second parameter 16, e. g. int('0x6E', 16) will give you the number 110.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.