Skip to content

Instantly share code, notes, and snippets.

@rikaardhosein
Created April 25, 2013 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rikaardhosein/5457031 to your computer and use it in GitHub Desktop.
Save rikaardhosein/5457031 to your computer and use it in GitHub Desktop.
def hex2bytes(hex_string):
bytes = bytearray()
for i in range(0,len(hex_string),2):
bytes.append( int(data[i:i+2],16) )
return bytes
def conv_chunk( chunk, i = 0, max = 4 ):
charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
return conv_chunk(chunk>>6,i+1,max)+(charset[(chunk)&0x3F]) if i < max else ''
def bytes2base64(bytes):
base64_string = ''
num_sections = len(bytes)/3
int_val = 0
for i in range(0,num_sections):
int_val = (bytes[0]<<16) + (bytes[1]<<8) + bytes[2]
base64_string += conv_chunk(int_val)
bytes = bytes[3:]
bytes_left = len(bytes)%3
if bytes_left > 0 :
int_val = bytes[0]<<4 if bytes_left==1 else (bytes[0]<<10)+(bytes[1]<<2)
base64_string += conv_chunk(int_val,max=bytes_left+1)+('='*(3-bytes_left))
return base64_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment