Working with bytes.
Anton Vredegoor
anton at vredegoor.doge.nl
Thu Apr 8 16:59:46 EDT 2004
anton at vredegoor.doge.nl (Anton Vredegoor) wrote:
> http://www.faqs.org/rfcs/rfc1924.html
Replying to my own post. I was using lowercase letters before
uppercase and did some other non compliant things. Because I was using
random data I didn't notice. The code below should reproduce the
rfc1924 example.
Anton
from binascii import hexlify
from string import digits, ascii_lowercase, ascii_uppercase
_rfc1924_letters = ascii_uppercase + ascii_lowercase
_rfc1924_chars = digits+_rfc1924_letters+'!#$%&()*+-;<=>?@^_`{|}~'
_rfc1924_table = dict([(c,i) for i,c in enumerate(_rfc1924_chars)])
_rfc1924_bases = [85L**i for i in range(19,-1,-1)]
def bytes_to_rfc1924(sixteen):
res = []
i = 0L
for byte in sixteen:
i <<= 8
i |= ord(byte)
for j in range(20):
i,k = divmod(i,85)
res.append(_rfc1924_chars[k])
res.reverse()
return "".join(res)
def rfc1924_to_bytes(twenty):
res = []
i = 0L
for b,byte in zip(_rfc1924_bases,twenty):
i += b * _rfc1924_table[byte]
for j in range(16):
i,k = divmod(i,256)
res.append(chr(k))
res.reverse()
return "".join(res)
def bytes_as_ipv6(bytes):
addr = [bytes[i:i+2] for i in range(0,16,2)]
return ":".join(map(hexlify,addr))
def test():
s = "4)+k&C#VzJ4br>0wv%Yp"
bytes = rfc1924_to_bytes(s)
check = bytes_to_rfc1924(bytes)
assert s == check
addr = bytes_as_ipv6(bytes)
print addr
if __name__=='__main__':
test()
output:
1080:0000:0000:0000:0008:0800:200c:417a
More information about the Python-list
mailing list