0

I am new to python and was trying to do a simple job but I am having a problem. I am trying to take a large number as input from user say 500 and write it to a file in hex format. For this I tried to take a small number as first step and write it, but I get the error as below

10 
0xa 
Traceback (most recent call last):
   File "temp.py", line 7, in <module>
    fp.write(bytes(('num',))) TypeError: 'str' object cannot be interpreted as an integer

The sample code used is as below.

intval = int(input())
num = hex(intval)
print(num)
with open('hexFile.iotabin', 'wb') as fp:
    fp.write(bytes(('num',)))
    fp.close()

Could you let me know

  1. What am I doing wrong here?
  2. For large number say 500, I would like to split it to two bytes while writing. Will to_bytes() be able to help once the issue above is resolved or is there any other simple way.
Xiddoc
  • 3,369
  • 3
  • 11
  • 37
sandeep
  • 141
  • 1
  • 1
  • 11

1 Answers1

1

1.

hex returns a string instead of a number. bytes(('num',)) should be bytes((intval,)).

This works for 0 - 255, i.e., 0x0 - 0xff:

intval = int(input())

with open("hexFile.iotabin", "wb") as fp:
    fp.write(bytes((intval,)))

And fp.close() is unnecessary since with will close the file.

2.

According to this answer, yes, to_bytes is helpful for numbers larger than 255.

def int_to_bytes(x: int) -> bytes:
    return x.to_bytes((x.bit_length() + 7) // 8, "big")


intval = int(input())

with open("hexFile.iotabin", "wb") as fp:
    fp.write(int_to_bytes(intval))
CCXXXI
  • 181
  • 2
  • 5