简体   繁体   中英

String/Binary data to Bytes

Am new to Python. I want to convert a char array to byte buffer ie Is there any way to convert data which could be string or binary data to byte buffer.

Eg: if str = 'apple' I need buffer = bytes values of 'apple' which I can access like buffer[i] and buffer[:j]

If i use map(ord,'apple') this returns a list but I need a continuos buffer. How do I get this in Python ?

UPDATE 1: Also I need in bytes because today it might be strings but tomorrow I might be dealing with files.

UPDATE 0: I want it in bytes. I could have used strings as @ignacio suggests but strings just wont do. Because eventually this will go into my implementation of rolling hash

Try bytearray . Which will convert the source string to an array of byte. There is an optional encoding parameter which you need to specify in case if the default encoding is not the current default string encoding.

Example

>>> s = 'apple'
>>> arr=bytearray(s)
>>> [x for x in arr]
[97, 112, 112, 108, 101]
>>> type(arr)
<type 'bytearray'>
>>> 

You could use struct module in python.

The struct module includes functions for converting between strings of bytes and native Python data types such as numbers and strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM