Help: C char bits operations to python converting

Fredrik Lundh effbot at telia.com
Wed Sep 27 11:28:13 EDT 2000


gangli at msn.com wrote:
> In article <8qst1l$rbj$1 at nnrp1.deja.com>,
>   fredrik at pythonware.com wrote:
> > gangli at msn.com wrote:
> > > > >How could I convert following C statments to Python?
> > > > >   char tmp_ch, tmp_ch0, tmp_ch1;
> > > > >   tmp_ch = 'K' - 'A';          /* -> 10 */
> > > > >   tmp_ch0 = ('N' - 'A') << 4;  /* -> -48 */
> > > > >   tmp_ch1 = tmp_ch+ tmp_ch0;   /* -> -38 */
> > > >
> > > > Use the built-in ord() function.
> > >
> > > It only help convert "tmp_ch = 'K' - 'A';", but not others
> >
> > it sure does.  try again.
> >
> 
> It does not:
> >>> (ord('N') - ord('A')) << 4
> 208

are you trying to solve a real problem, or an is this just
some kind of homework?

(if it's a real problem, note that your C code isn't portable)

anyway, to "cast" a python integer to an 8-bit signed
integer, mask with 255 and subtract 256 from it if it's
larger than 127:

    def char(value):
        value = value & 255
        if value > 127:
            return value - 256
        return value

</F>




More information about the Python-list mailing list