0

I need to create a file which contains only hex data.

Suppose I have an integer value 10, I want hexadecimal 'a' the value written to the file. The file should have only 1 byte size.

I tried the format, binascci.hexlify etc but it is not giving the correct solution. If I directly use hex(10), it will add 0x to the file.

If I write 25, the file will contain two characters 1 and 9 (25(dec) = 19(hex))

Kindly let me know the correct mechanism.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Your question is unclear. Do you want the contents of the file to be `b'a'` or `b'\x0a'` or something else? – Aran-Fey Mar 25 '19 at 09:45
  • I am not familiar with the " b' " term. What I want is simple. say value = 25. I want to write value to a file. Since 25 needs only one byte, when I write it to the file it should be 1 byte long only. The file size will ultimately be 1 byte – Ison Thomas Mar 25 '19 at 09:47
  • 1
    Okay, let's take this step by step. Is the file supposed to be a text file, containing the letter "a"? Or is it supposed to be a binary file, containing a byte with the value 10? – Aran-Fey Mar 25 '19 at 09:50
  • It must be a binary file containing a byte with the value 10 – Ison Thomas Mar 25 '19 at 09:50
  • 1
    So then this answers your question, right? [How can I write 1 byte to a binary file in python](//stackoverflow.com/q/39364905) – Aran-Fey Mar 25 '19 at 09:53
  • I just saw the chr method. chr(value) is converting it into 1 byte. That is working for me. Thanks for the help – Ison Thomas Mar 25 '19 at 09:57

3 Answers3

0

See the hex() documentation:

>>> '%#x' % 15, '%x' % 15, '%X' % 15
('0xf', 'f', 'F')
>>> format(15, '#x'), format(15, 'x'), format(15, 'X')
('0xf', 'f', 'F')
>>> f'{15:#x}', f'{15:x}', f'{15:X}'
('0xf', 'f', 'F')
Jurgen Strydom
  • 3,540
  • 1
  • 23
  • 30
0
format(10,'x')
format(25,'x')

output

'a'
'19'
paradox
  • 602
  • 6
  • 13
0
"{:x}".format(i)

If you want to make a function out of this:

enhex = "{:x}".format
David Jones
  • 4,766
  • 3
  • 32
  • 45