[Tutor] stumped again adding bytes

shawn bright nephish at gmail.com
Fri Feb 23 22:02:56 CET 2007


ok, i am good with what you have explained here,
now i am on a similar problem.

the data i need is in a condensed format. in other words, they are
sending 2 values in three bytes.

so if i have 3 values say a = 53, b = 13, and c = 31

so value 1 is the first byte ( a ) and the first 4 bits of the second byte (b)
value 2 is the last 4 bits of byte (b) and byte (c)

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

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.

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

thanks

shawn


On 2/21/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> shawn bright wrote:
> > oh, sorry, i meant how to get the 0x0A27 out of two bytes
> > a = 0x27 and b = 0x8A
> I don't see what the number 0x0A27 has to do with bytes 0x27 and 0x8A,
> but I'll assume you meant
> 0x0A for b.
> >
> > actually, in my script, i am not using the hex values at all, i have
> > these because they are examples in the documentation of a machine i am
> > talking to. i am actually using ord(a) and ord(b) to get digital
> > values of the numbers
> >
> > so, i guess a better question is how to get 2599 from the ord(a) and
> > ord(b), how do i put the two bytes together to make one number?
> Well, if you have the bytes originally, instead of ording them, hex them.
> so... given these bytes
> bytelist = [chr(0x27),chr(0x8A)]
> hexlist = []
> for item in bytelist:
>  hexlist.append(hex(item)[2:].zfill(2))
>
> print int('0x' + ''.join(hexlist) , 16)
>
> A less roundabout way to do this:
>
> given the number
> 0x0A,
> this is stored in the system the same as the number 10.
>  >>> 0x0A
> 10
> As you can see.
> So having the ord values is okay, because they're the same values as the
> hex of the bytes, just represented in a different base.
> Okay, now we'll assume that a byte is 8 bits.
> Because of this, we know that the number
> 0xFFEE
> is the same as
> (0xFF << 8) + 0xEE
> In other words, the higher byte is shifted over by 8 bits, and the other
> value is not shifted.
> This idea could easily be expanded to encompass byte strings of any length.
> Oh, and in the case of your example values,
>  >>> (0x0A << 8) + 0x27
> 2599
>
> Note that the + operator has higher (or the same?) precedence than the
> binary shift left.
> This means that the value 0x0A will be shifted by 8+0x27 times if the
> parenthesis are missing.
>
> Other equivalent operations:
>  >>> 0x0A * 256 + 0x27
> 2599
>  >>> 0x0A * 2**8 + 0x27
> 2599
>
> But like Kent said, you probably should use struct or something like that.
> Just in case you're interested, I'm sending this e-mail as well.
> HTH,
> -Luke
> >>
> >
>
>


More information about the Tutor mailing list