开发者

Translate several lines of C to Python [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

I need just a little bit of help translating C to python. I h开发者_如何转开发ave not used c++ in about 4 years now, and when I used it, I only new the basics. the context of this snippet is reading a file and creating a checksum

int ff7_checksum( void* qw )
{
   int i = 0, t, d;
   long r = 0xFFFF, len = 4336;
   long pbit = 0x8000;
   char* b=(char*)qw;

   while( len-- ) {
      t = b[i++];
      r ^= t << 8;
      for(d=0;d<8;d++) {
         if( r & pbit )
            r = ( r << 1 ) ^ 0x1021;
         else
            r <<= 1;
      }
      r &= ( 1 << 16 ) - 1;
   }
   return (r^0xFFFF)&0xFFFF;
}


I assume that qw points at a buffer with a known size (4336) and that does not really represent a string (i.e. it might contain \0 characters that should still be processed).

However, in Python (2.x), we still generally model this as a string, since the string may contain embedded \0 bytes, and knows its own length. There is thus also no reason to hard-code the length.

More idiomatically, we get something like:

def ff7_checksum(data): # data used to be 'qw'
  all_bits = 0xFFFF # a 16-bit value with all bits set.
  result = all_bits # result used to be 'r'
  pbit = 0x8000 # the highest-order bit in a 16-bit value.

  for byte in data: # byte used to be 't'
    result ^= byte << 8
    for i in range(8):
      result = (result << 1) ^ (0x1021 if result & pbit else 0)
    result &= all_bits
  return result ^ all_bits # the original &-mask is not necessary
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜