Multiple characters in Python ord function
Asked Answered
J

1

7

Programming beginner here. (Python 2.7)

Is there a work around for using more than a single character for Python's ord function?

For example, I have a hex string '\xff\x1a' which I'd like the decimal value for so that I can sum it with other hex strings. However ord only accepts a single hex string character.

Thank you!

Jaxartes answered 28/1, 2015 at 0:13 Comment(4)
remember that strings are iterable by character...Madoc
How the solution below, Micuzzo?Farad
What do you mean by decimal value? ord() works on a byte, and that string contains two bytes.Mayest
@AshwiniChaudhary yes you are correct. My intention is to sum a series of hex values and from my understanding the best way to do this is to convert them into a integer and then sum... then reconvert to hex.Jaxartes
F
11

Strings are iterable, so you can loop through the string, use ord and add the results:

your_sum = sum([ord(i) for i in '\xff\x1a'])
Farad answered 28/1, 2015 at 0:14 Comment(7)
Thank you. This seem to work very well. Unfortunately I don't have enough reputation to up vote you...Jaxartes
Just mark the solution as answer, and I will be rewarded.Farad
Thanks. By the way, what purpose does this code serve?Farad
I will copy what I wrote to Ashwini here:My intention is to sum a series of hex values and from my understanding the best way to do this is to convert them into a integer and then sum... then reconvert to hex.Jaxartes
@micuzzo: You don't have a series of hex values, you just have a series of bytes. '\x40' is just one byte, print it and you'll see @.Suspicious
Gematria!Gaddis
Come on people! Use a generator expression rather than wasting memory and CPU cycles creating an intermediate list: your_sum = sum(ord(i) for i in '\xff\x1a').Lilylivered

© 2022 - 2024 — McMap. All rights reserved.