[Tutor] stumped again adding bytes

Alan Gauld alan.gauld at btinternet.com
Sat Feb 24 02:54:11 CET 2007


"shawn bright" <nephish at gmail.com> wrote


> so i believe i do shifting here. as in i do a
> (a << 4) * 32 + b
>

Don't use shifting to extract the bits, use a bitmask
and & its much easier.

If you want to extract the left-most 4 bits use 0xf0
If you want to extract the righ-most bits use 0x0f

1 & 1 = 1
1 & 0 = 0

Or more generically:

1 & A = A

right = data & 0xf0
left = data & 0x0f

As easy as that.

Now if you need to stich the bits together you need to move
one element up by 4 bits which is where shifting comes in.

result = (data << 4) & right

> but i am not getting what i think that i should be, and i think it's
> because i am not getting rid of the bytes that i am not using.

Its easier to extract the bits into a new variable using a mask
as shown.

> i have looked at the struct module, but can't figgure out how to do
> this type of thing with it.

This is not what struct is for, don't try uising it for this. even if
you make it work its not the best tool.

Alan G. 




More information about the Tutor mailing list