Bit Operations

John Machin sjmachin at lexicon.net
Wed Nov 28 15:37:29 EST 2007


On Nov 29, 7:07 am, "Gianmaria Iaculo - NVENTA"
<gianma... 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.

But a nibble is 4 bits and a char in general is 8 bits. Please explain
"write A to the high nibble". Let's assume that you mean that 0 <= A
<= 15 ....

The building blocks that you need are the ord() and chr() builtin
functions, and the << (shift-left) operator. The hex() function is
useful for seeing what is happening.

>>> a = '\x07'
>>> b = '\x08'
>>> c = 7
>>> d = 8
>>> ord(a)
7
>>> chr(c)
'\x07'
>>> hex(c)
'0x7'
>>> hex(c << 4)
'0x70'
>>> hex((ord(a) << 4) + ord(b))
'0x78'
>>> hex((c << 4) + d)
'0x78'
>>>

Cheers,
John



More information about the Python-list mailing list