본문 바로가기
Programming/Python

python - dumpcode

by bbolmin 2014. 2. 26.




c언어의 dumpcode.h 기능을 python에서 사용하기 위해 만들었다.

코드가 좀 지저분하다;;




import sys, struct, string

def hexdump(data, align_size=1, baseaddr=0x00000000):
    '''
    data = Dump data
    align_size = 1, 2, 4 (byte, word, dword)
    baseaddr = Base Address 
    '''
    if not (align_size in (1, 2, 4)):
        return False
    if len(data)%align_size != 0 :
        return False
    
    ascii_data = ''
    for i in range(0, len(data), align_size):

        ### print address ###
        if i%16 == 0:
            sys.stdout.write(' ' + ascii_data)  ### print ascii data ###
            ascii_data = ''
            sys.stdout.write('\n0x%s ' % struct.pack('>I', baseaddr).encode('hex'))
            baseaddr += 0x10
            

        ### print hex data ###
        tmp = data[i:i+align_size]
        hex_data = ''
        
        for j in range(1, align_size+1):
            hex_data += tmp[-j]
            if tmp[-j] in string.digits+string.ascii_letters+string.punctuation:
                ascii_data += tmp[-j]
            else:
                ascii_data += '.'
        ascii_data += ' '
            
        hex_data = hex_data.encode('hex')
        
        if align_size != 1:
            sys.stdout.write('0x%s ' % hex_data)
        else:
            ascii_data = ascii_data.replace(' ', '')
            sys.stdout.write('%s ' % hex_data)
            
        ### print last ascii data ###
        if i == range(0, len(data), align_size)[-1]:
            length = 16-len(ascii_data.replace(' ', ''))
            
            if align_size == 4:
                space = (' '*11)*(length/4)
            elif align_size == 2:
                space = (' '*7)*(length/2)
            else:
                space = (' '*3)*length
                
                
            sys.stdout.write(space + ' ' + ascii_data)
            ascii_data = ''
    sys.stdout.write('\n')
    


### test ###
if __name__ == '__main__':
    data = 'aabbccddaabbccdd'*2

    hexdump(data, 4, 0x10000000)
    hexdump(data, 2, 0xbf000000)
    hexdump(data, 1)

        
    


[ 결과 ]






'Programming > Python' 카테고리의 다른 글

python - 인코딩 관련  (0) 2014.03.02
python - Thread 사용  (1) 2014.03.01
python - ROL, ROR  (2) 2013.12.14
RC4 알고리즘 - python  (1) 2013.12.14
python HTML, XML 파싱 - BeautifulSoup  (0) 2013.11.21