On Jul 24, 3:28 pm, superpollo <u...@example.net> wrote: > is there a pythonic and synthetic way (maybe some standard module) to > "pack" an integer (maybe a *VERY* big one) into a string? like this: > > >>> number = 252509952 > >>> hex(number) > '0xf0cff00' > >>> > > so i would like a string like '\xf0\xcf\xf0\x00' > > i wrote some code to do it, so ugly i am ashamed to post :-( > > i tried xdrlib, but does not quite do what i mean... > > bye
This works, I think. >>> def hex_string(n): ... a = hex(n) ... ch_list = [] ... if a.startswith('0x'): a = a[2:] ... if a.endswith('L'): a = a[:-1] ... for i in range(0, len(a)): ... ch_list.append(chr(int(a[i:i+2],16))) ... return ''.join(ch_list) ... >>> hex_string(252509952) '\xf0\x0c\xcf\xff\xf0\x00\x00' >>> hex_string(283691163101781L) '\x10\x02 \x03?\xff\xf0\x00\n\xaa\xa5U\x05' >>> -- http://mail.python.org/mailman/listinfo/python-list