Bit Operations

Chris Mellon arkanes at gmail.com
Wed Nov 28 15:27:10 EST 2007


On Nov 28, 2007 2:07 PM, Gianmaria Iaculo - NVENTA
<gianmaria at hotmail.com> wrote:
> Hi there,
> I'm so new to python (coming from .net so excuse me for the stupid question)
> and i'm tring to do a very simple thing,with bytes.
>
> My problem is this:
>
> i've a byte that naturally is composed from 2 nibbles hi&low, and two
> chars.. like A nd B. What i wonna do is to write A to the High nibble and B
> to the the lower nibble.

A string in python is a sequence of bytes, so what you're describing
here is the string "AB".

> Or an other example can be i've 2 numbers.. like 7 and 8 and whant to do the
> same as for chars.
>

"\x07\x08"

> I'm really confused on how t do it, maybe cause python is type-less (dynamic
> typed)
>

You can use the struct module to convert back and forth between byte
sequences and numerical values. For example, to get an integer with
the value of the nibble you mentioned before:

struct.unpack("h", "AB") -> (16961,)

Exactly what you'll want to use and what format you want will depend
on why you're doing this.



More information about the Python-list mailing list