Open DonaldTsang opened 5 years ago
partial solution
x = ['!','$','%','(',')','*','+',',','-','.','0','1','2','3','4','5',
'6','7','8','9',';','=','>','@','A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X',
'Y','Z','[',']','^','_','`','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y',
'z','{','|','}','~']
b = b"\xFE\xE1\xDE\xAD"
def encode_chunk(byte):
assert type(byte) == bytes and len(byte) == 4
accum = sum([byte[i]<<(8*(3-i)) for i in range(4)])
return "".join([x[(accum//(85**(4-i)))%85] for i in range(5)])
def decode_chunk(string):
assert type(string) == str and len(string) == 5
accum = sum([x.index(string[i])*(85**(4-i)) for i in range(5)])
return b"".join([bytes([(accum>>(8*(3-i)))&255]) for i in range(4)])
def encode_byte(byte):
assert type(byte) == bytes
byte = [byte[i:i+4] for i in range(0, len(byte), 4)]
return "".join([encode_chunk(i) for i in byte])
def decode_byte(string):
assert type(string) == str
string = [string[i:i+5] for i in range(0, len(string), 5)]
return b"".join([decode_chunk(i) for i in string])
Yes, if you'd like to help out with implementations in other languages, I'll include them here :)
The C implementation was only intended as a lowest common denominator reference implementation, since all languages have C bindings.
Made a useful class for this
class conversion:
char_set, byte_count, char_chunk, base = None, None, None, None
def conversion(self,char_set,byte_count,char_chunk,base):
self.char_set = char_set
self.byte_count = byte_count
self.char_chunk = char_chunk
self.base = base
def encode_chunk(self,byte):
assert type(byte) == bytes and len(byte) == self.byte_count
accum = sum([byte[i]<<(8*(self.byte_count-i-1)) for i in range(self.byte_count)])
return "".join([x[(accum//(self.base**(self.char_chunk-i-1)))%self.base] for i in range(self.char_chunk)])
def decode_chunk(self,string):
assert type(string) == str and len(string) == self.char_chunk
accum = sum([x.index(string[i])*(self.base**(self.char_chunk-i-1)) for i in range(self.char_chunk)])
return b"".join([bytes([(accum>>(8*(self.byte_count-i-1)))&255]) for i in range(self.byte_count)])
def encode_byte(self,byte):
assert type(byte) == bytes
byte = [byte[i:i+self.byte_count] for i in range(0, len(byte), self.byte_count)]
return "".join([self.encode_chunk(i) for i in byte])
def decode_byte(self,string):
assert type(string) == str
string = [string[i:i+self.char_chunk] for i in range(0, len(string), self.char_chunk)]
return b"".join([self.decode_chunk(i) for i in string])
Python would be used for toying around and general scripting. JS implementation woulb be used for web applications.