9

I want to get a list of ints representing the bytes in a string.

6
  • If you don't mean ASCII values (as you wrote in a comment below), what do you mean? Commented Jul 15, 2010 at 13:49
  • Can you give an example of what the string looks like if you are not interested in the ascii values? Commented Jul 15, 2010 at 13:50
  • Are you trying to convert string to int - in that case, see my answer - and somebody give me a MindReader badge ;) Commented Jul 15, 2010 at 13:56
  • 2
    Shall we bet on it (I doubt that's what he wants)? Hey, feature request for meta: Bet rep points on what a question means, winner takes all. Commented Jul 15, 2010 at 14:05
  • @Tim In that case, another option that I can think of is to convert "00010100" to 20 and so on - who wanna bet on that ;-) Commented Jul 15, 2010 at 14:12

3 Answers 3

14

One option for Python 2.6 and later is to use a bytearray:

>>> b = bytearray('hello')
>>> b[0]
104
>>> b[1]
101
>>> list(b)
[104, 101, 108, 108, 111]

For Python 3.x you'd need a bytes object rather than a string in any case and so could just do this:

>>> b = b'hello'
>>> list(b)
[104, 101, 108, 108, 111]
Sign up to request clarification or add additional context in comments.

1 Comment

To clarify for the OP, these values are the ascii values.
7

Do you mean the ascii values?

nums = [ord(c) for c in mystring]

or

nums = []
for chr in mystring:
    nums.append(ord(chr))

Comments

2

Perhaps you mean a string of bytes, for example received over the net, representing a couple of integer values?

In that case you can "unpack" the string into the integer values by using unpack() and specifying "i" for integer as the format string.

See: http://docs.python.org/library/struct.html

Comments

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.