Bit Operations

Grant Edwards grante at visi.com
Wed Nov 28 15:42:45 EST 2007


On 2007-11-28, Chris Mellon <arkanes at gmail.com> wrote:
> 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".

No, he's describing something that consists of 2 nibbles (1
byte).  The string "AB" is two bytes.

>> 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"

Again, he wants a single byte and that's two bytes.

>> 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,)

No, he wants to do this:

 (0x0A<<4) | 0x0B

 (7<<4) | 8

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


-- 
Grant Edwards                   grante             Yow! My vaseline is
                                  at               RUNNING...
                               visi.com            



More information about the Python-list mailing list