An implementation of a64l as from the c stdlib. Convert between a radix-64 ASCII string and a 32-bit integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | def a64l(s):
"""
An implementation of a64l as from the c stdlib.
Convert between a radix-64 ASCII string and a 32-bit integer.
'.' (dot) for 0, '/' for 1, '0' through '9' for [2,11],
'A' through 'Z' for [12,37], and 'a' through 'z' for [38,63].
TODO:
do some implementations use '' instead of '.' for 0?
>>> a64l('.')
0
>>> a64l('ZZZZZZ')
40359057765L
#only the first 6 chars are significant
>>> a64l('ZZZZZZ.')
40359057765L
>>> a64l('A')
12
>>> a64l('Chris')
951810894
"""
MASK = 0xffffffff
BITSPERCHAR = 6
orda, ordZ, ordA, ord9, ord0 = ord('a'), ord('Z'), ord('A'), ord('9'), ord('0')
r = 0
for shift, c in enumerate(s[:6]):
c = ord(c)
if c > ordZ:
c -= orda - ordZ - 1
if c > ord9:
c -= ordA - ord9 - 1
r = (r | ((c - (ord0 - 2)) << (shift * BITSPERCHAR))) & MASK
return r
|
Tags: conversion, radix64
The algorithm is incorrect.
In python3 on linux system:
The use and output of this program is:
Beats me, Chris. I hope I've convinced you that your code does not match my a64l. When I do the conversion by hand using mathematica I get your result for 6 capital zees. Or with python:
Therefor, either we do not understand this representation, or the a64l distributed with my linux is incorrect.
Wow. I guess I'll ask redhat or the makers of my libc.
When I insert this line into my c program I find that l64a writes ZZZZZ/
Perhaps negative numbers are the trouble???? No. (Note that 0 is the empty string, but the digit 0 used as a place holder is "."
OK, before I call redhat, let's check the binary representations of these numbers AH!
6 bits per character, but 6 is not a factor of 32. The sixth character can only be ., /, 0, or 1. So, your code works for some range of positive numbers. It is clearly not a replacement for the lib c versions. My vote stands at -1, the python 3.0 (final released today) library ctypes document shows how to use libc in the microsoft environment.