0

Am new to Python. I want to convert a char array to byte buffer i.e. 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

3
  • What's wrong with slicing the string? Commented Dec 12, 2011 at 8:33
  • i want it in bytes. strings just wont do. because eventually this will go into my implementation of rolling hash. Commented Dec 12, 2011 at 8:41
  • If you're using Python 3.x then that's important information that needs to go into the question. Commented Dec 12, 2011 at 8:42

2 Answers 2

3

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'>
>>> 
Sign up to request clarification or add additional context in comments.

4 Comments

abhijit, thanks for reply. But i dont want the bytes in a list. I want it in a buffer. If I wanted it in a list I could have used ord itself. But later I might want to convert a file to bytes. In this scenario a byte buffer will make sense. It answers all my usecases. So how do I get this in a buffer instead of a list ?
Its not a list but an array. Just see the type of the variable created. I have used the list comprehension to just list of the content but its stored as a byte array. Hope this makes sense.
Is bytearray just like a buffer. can I do arr[i] etc ?
yes you can. You can access the individual elements by indexing and also bytearray is mutable i.e. you can assign values to individual indexed element.
0

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.

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.