Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert bytes in a string to integers? Python

Tags:

python

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

like image 629
Juanjo Conti Avatar asked Jul 15 '10 13:07

Juanjo Conti


People also ask

How do you convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do I convert a string to an int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

How do I convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable. The simplest way to do so is using valueOf() method of String class in java. lang package.


2 Answers

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]
like image 169
Scott Griffiths Avatar answered Nov 10 '22 15:11

Scott Griffiths


Do you mean the ascii values?

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

or

nums = []
for chr in mystring:
    nums.append(ord(chr))
like image 7
Donald Miner Avatar answered Nov 10 '22 17:11

Donald Miner