简体   繁体   中英

Count up hex string in python (\x00 …\xff)

I want to count up the string "\\x00" like this:

\\x01 , \\x02 , \\x03 , \\x04 .... \\xff , and than again \\x00 ... etc.

But I can't figure out how to do that.

I tried something like that:

counter= "\x00"
for i in range(1, 2000):
    counter= int(counter,16) +1

But it obviously did not work : invalid literal for int() with base 16: '\\x00'

I hope you guys have an better idea. Thanks a lot!

You can convert an int to the corresponding character with the chr(..) [Python-doc] builtin.

So we can for example construct such string with:

from itertools import chain

''.join(chr(i) for i in chain(range(256), range(254, -1, -1)))

This gives us:

>>> ''.join(chr(i) for i in chain(range(256), range(254, -1, -1)))
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0¡¢£¤¥¦§¨©ª«¬\xad®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿþýüûúùø÷öõôóòñðïîíìëêéèçæåäãâáàßÞÝÜÛÚÙØ×ÖÕÔÓÒÑÐÏÎÍÌËÊÉÈÇÆÅÄÃÂÁÀ¿¾½¼»º¹¸·¶µ´³²±°¯®\xad¬«ª©¨§¦¥¤£¢¡\xa0\x9f\x9e\x9d\x9c\x9b\x9a\x99\x98\x97\x96\x95\x94\x93\x92\x91\x90\x8f\x8e\x8d\x8c\x8b\x8a\x89\x88\x87\x86\x85\x84\x83\x82\x81\x80\x7f~}|{zyxwvutsrqponmlkjihgfedcba`_^]\\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)(\'&%$#"! \x1f\x1e\x1d\x1c\x1b\x1a\x19\x18\x17\x16\x15\x14\x13\x12\x11\x10\x0f\x0e\r\x0c\x0b\n\t\x08\x07\x06\x05\x04\x03\x02\x01\x00'

or in a similar way print the characters:

for i in range(256):
    print(chr(i))
for i in range(254, -1, -1):
    print(chr(i))
from itertools import cycle
hx = lambda i: '\\x' + hex(i//16)[2:] + hex(i%16)[2:]
counter = cycle(map(hx, range(256)))
for i in range(2000):
    print(next(counter))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM