How to represent a sequence of raw bytes

Tino Wildenhain tino at wildenhain.de
Mon Dec 22 02:06:53 EST 2008


Steven Woody wrote:
> On Mon, Dec 22, 2008 at 10:27 AM, Michiel Overtoom <motoom at xs4all.nl> wrote:
>> On Monday 22 December 2008 03:23:03 Steven Woody wrote:
>>
>>> 2.  char buf[] = {0x11, 0x22, 0x33, ... }
>>>
>>> What's the equivalent representation for above in Python?
>>>>> buf="\x11\x22\33"
...

> I thing "\x11\x22\x33" in python is not the {0x11, 0x22, 0x33} in C.
> Since, a string in python is immutable, I can _not_ do something like:
>  b[1] = "\x55".
> 
> And, how about char buf[200] in my original question?  The intension
> is to allocate 200 undefined bytes in memory. Thanks.

Well in most cases you don't need to do that, instead you could assemble
your stream on the way out based on sequences, generators etc.

Please note that char in your example is just a bit inapropriate (but
common in C) shorthand for unsigned short int. There is no such type
in python so you could use int() if you want to operate on the numeric
value. Depending on your use case a big integer could also serve well
and you can convert it into a byte string.

If you want random access to the bytes, you can use list or array (see 
array module) or, if you want it with much more performance resort
to numpy, scipy, they have arrays similar to C and also much more
numeric datatypes.

Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20081222/45096512/attachment-0001.bin>


More information about the Python-list mailing list