Python Forum

Full Version: Trouble converting numbers to characters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm reading numbers from a file which I want to write to a separate file as the ascii hex of the numbers. So, e.g., if I read in ff, I want to write out '0xff'. My code (below; just printing to console for now) works fine for some values, but not for others. Specifically, it can read/write ff (as above), but when it reads 80, it writes "0x20ac". This seems to be because it interprets 80 as a unicode character whose hex value is 0x20ac (8364 decimal). What am I doing wrong? Misusing hex() and/or ord()? Thanks for any tips.

# Open output file

with open("E:\\Karl\\Documents\\Sculpture\\Prime Time\\Digits\\1d_inv_conv.c", 'w') as g:

# Open input file for reading in text mode

    with open("E:\\Karl\\Documents\\Sculpture\\Prime Time\\Digits\\1d_inv2.pbm", 'rt') as f:
        f.read(10)      # Skip header
        while True:
            x = f.read(1)
            if x == '':     # End of file?
                sys.exit()
            print(hex(ord(x)))
Probably I don't get the problem, but ord() is for single characters:

>>> help(ord)
Help on built-in function ord in module builtins:

ord(c, /)
    Return the Unicode code point for a one-character string.
(END)
This means that you can't use representation of 80 as string for ord() argument:

>>> ord('80')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found


One can do:

>>> print(*(hex(ord(x)) for x in '80'))
0x38 0x30
The contents of the part of the file that are producing the erroneous behavior are
FF FF FF 80 03
FF FF FF 00 03
If I run print (ord(x)) on this section, the output is
255
255
255
8364
3
255
255
255
0
3
I'm trying to figure out why that 80 (0x80) is being read as 8364 (0x20ac which is how it gets written to the file, even though print (hex(ord(8364))) throws an error).
I don't understand how you run ord() on these without error. What I get:

>>> ord(FF)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'FF' is not defined
>>> ord('FF')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
Well, they worked for me except for that exception. I’ve since reworked the code without the ord() and it’s working fine now.