Idiomatic way to port C bitfiddling to Python -


how port following c code in pythonic way (especially bit fiddling part in get2, get3, ...)

switch(mem[pos-1]) {   ...   case 0x10: pos+=get2(&mem[pos+0x02])+0x04; break;   case 0x11: pos+=get3(&mem[pos+0x0f])+0x12; break;   case 0x16: pos+=get4(&mem[pos+0x00])+0x04; break;   ...   case 0x20: pos+=0x02; break; }  ...  ////////////////////////////////////////////////////////// // conversion routines fetch bytes in big endian order //////////////////////////////////////////////////////////  unsigned int get2(unsigned char *pointer) {   return (pointer[0] | (pointer[1]<<8)); }  unsigned int get3(unsigned char *pointer) {   return (pointer[0] | (pointer[1]<<8) | (pointer[2]<<16)); }  unsigned int get4(unsigned char *pointer) {   return (pointer[0] | (pointer[1]<<8) | (pointer[2]<<16) | (pointer[3]<<24)); } 

this i've got far:

    x = struct.unpack('b', mem[pos-1])[0]      if x == 0x10:         # pos += ???         continue      if x == 0x11:         # pos += ???         continue      if x == 0x16:         # pos += ???         continue      if x == 0x20:          pos += 0x02         continue 

if you're getting 1 unsigned byte, do

x = ord(mem[pos - 1]) 

on python 2 or

x = mem[pos - 1] 

on python 3.

instead of select / case, want dictionary.

positions = {0x10: do_10, 0x11: do_12, 0x16: do_16} 

where do_10 etc. functions:

def do_10(pos):     # need endianness character     return struct.unpack('h', mem[pos + 0x02])[0] + 0x04 

you use this:

pos += positions[mem[pos - 1]](pos) 

if want define functions right in dictionary, can:

positions = {     # need endianness character     0x10: (lambda pos: struct.unpack('h', mem[pos + 0x02])[0] + 0x04)     # ...     } 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -