trouble converting c++ bitshift to python equivalent
Steve Holden
steve at holdenweb.com
Thu May 24 16:30:19 EDT 2007
nanodust at gmail.com wrote:
> hello all
>
> i am relatively new to python, catching on, but getting stuck on
> simple thing:
>
> i have two string bytes i need to push into a single (short) int, like
> so in c:
>
> temp = strBuf[2];
>
> temp = (temp<<7)+(strBuf[1]);
>
> c code works, but having trouble getting python to perform same
> function!
>
> keep getting type & operator errors (i apparently can't bitshift on
> str or int?)
>
> curious what the best way is to do this, in python...
>
> i'll stick w/ it & post when i sort it
>
>
> meanwhile, any help greatly appreciated
>
You should really use the struct module for that type of conversion, but
you also need to know that indexing of lists and tuples starts at 0, not 1.
For the specific case that you're discussing, you could convert each
character to its corresponding integer value and use shifting and adding
with those:
temp = (ord(strBuf[1]) << 8) + ord(strBuf[0])
Obviously if the byte order is wrong you would need to reverse the 0 and
1 elements.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com squidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------
More information about the Python-list
mailing list