python xxd.py将数据以xxd格式打印

来源:互联网 发布:数据有效性结合offset 编辑:程序博客网 时间:2024/06/05 02:58
当你在使用Python接收网络数据的时候,并且希望能以xxd漂亮的格式打印数据的时候,下面的代码或许对你有所帮助。
</pre><pre code_snippet_id="227616" snippet_file_name="blog_20140310_1_2104289" name="code" class="python">#!  /usr/bin/python3# author:zhangys# date:20140310 import stringimport struct __all__ = [ "xxd_bin" ,"xxd_str" ,"line_len"] __version__ = "1.0.0" line_len = 16 """@binarys bytesreturn noneprint @binarys as xxd like style"""def xxd_bin(binarys):    counter = 0    for i in range(0,len(binarys),line_len):        line = binarys[i:i + line_len]        # turn byte to hex str        buf2 = ['%02x' % i for i in line]        print( '{0}: {1:<39}  {2}'.format(('%07x' % (counter * 16)),        ' '.join([''.join(buf2[i:i + 2]) for i in range(0, len(buf2), 2)]),        ''.join([chr(b) if chr(b) in string.printable[:-5] else '.' for b in line])))         counter += 1     return """@buf strreturn noneprint @buf as xxd like style"""def xxd_str(buf):    counter = 0    for i in range(0,len(buf),line_len):        line = buf[i:i + line_len]        buf2 = ['%02x' % ord(i) for i in line]         print( '{0}: {1:<39}  {2}'.format(('%07x' % (counter * 16)),        ' '.join([''.join(buf2[i:i + 2]) for i in range(0, len(buf2), 2)]),        ''.join([c if c in string.printable[:-5] else '.' for c in line])))         counter += 1    return if __name__ == "__main__":    s = "asdfhjjl;;p009888hhnncbbbc"    xxd_bin(bytes(s,"ASCii"))    xxd_str(s)

0 0
原创粉丝点击