1

I got a string like:

s = "\0x01\0x02\0x01\0x11"

And I want to get the average number of that string. I tried this:

sum = 0
for d in s:
    sum += int(d)

But it said "invalid literal for int() with base 10:'\x08'" :-(

3
  • 1
    What have you tried? Commented Feb 28, 2013 at 3:06
  • Do you really want that last value to be 11? Commented Feb 28, 2013 at 3:29
  • Do you mean s = "\x01\x02\x01\x11"? Commented Feb 28, 2013 at 3:33

4 Answers 4

3

I recommend the struct module.

>>> import struct
>>> s = '\x01\x02\x01\x11'
>>> struct.unpack('=4B', s)
(1, 2, 1, 17)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the python int() function, the first argument is the string, the second is the base of the number.

You need to check the base, because what you posted looks like hexadecimal numbers (0x0 usually denotes a HEX number, additionally 02 is not a valid binary number).

For binary (base two):

num = int("0x11", 2); # num will be 3

For hexadecimal (base 16):

num = int("0x0A", 16); # num will be 10

To convert your string ("\0x01\0x02\0x01\0x11"):

numbers = [int(s, base) for s in "\\0x01\\0x02\\0x01\\0x11".split("\\") if len(s)]

If run with base = 16, outputs: numbers = [1, 2, 1, 17]

You can then find the average using:

average = sum(numbers)/len(numbers)

Comments

0

The ord() will, when given a string of length one, give you the code point of the character in that string. You should just be able to use this instead of int() in your code, which would look something like this:

sum = 0
for d in s:
    sum += ord(d)

Comments

0

You can do it like this:

s = "\0x01\0x02\0x01\0x11"
list = s.split('\0x')
list.remove('')

sum = 0
for d in list:
    sum += int(d)

# 15

1 Comment

These numbers are normally base 16 so \0x11 is actaully 17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.