0

I have a file in .ktx format. I have opened the file in 'rb' mode. I want to modify particular bytes in that file. I am reading bytes using read(4) [ i want to read number which is of 4 bytes], call and convert each chunk into a number. What I want is, to increase that number by specific number and insert it back into file stream. Is there any function in python which converts a byte string to an integer? I tried with int() but it prints some binary data.

my code:

bytes=file.read(4)
for char in bytes:
    print hex(ord(char))
debonair
  • 2,505
  • 4
  • 33
  • 73

2 Answers2

2
bytes = file.read(4)
bytesAsInt = struct.unpack("l",bytes)
do_something_with_int(bytesAsInt)

I think might be what you are looking for ... its hard to tell from the question though

here is the docs on the struct module https://docs.python.org/3/library/struct.html

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
-1

Try this

How can I convert a character to a integer in Python, and viceversa?

Here is a suggested workflow for what you seem to be wanting to do

  • Read the data
  • Convert the data to integer
  • Add X to the integer, where X is the value you want to increase by
Community
  • 1
  • 1
VampyreSix
  • 101
  • 3
  • 1
    The OP is dealing with packed binary data, not python `int`s. – roippi May 19 '14 at 18:57
  • Bytes are characters no matter which language you are programming in, failing to see how converting a char to a corresponding numeric value is not applicable. – VampyreSix May 19 '14 at 19:02
  • In his own example, he is iterating one char at a time. so this fits with his actual work so far. – VampyreSix May 19 '14 at 19:02
  • He is iterating one char at a time *incorrectly*, so posting another incorrect answer that follows his method is not useful. – roippi May 19 '14 at 19:04
  • You state that he is incorrectly doing this, but at the same time voted to close cause of ambiguity, while downvoting all answers here. You are an asset to the community. – VampyreSix May 19 '14 at 19:11