1

For example, say I perform

base64.b64encode('Monday')

to obtain 'TW9uZGF5'. But when I want to access the 6 bits for each of the characters, I get something like this (the ASCII values for each of these characters):

[84 87 57 117 90 71 70 53]

when I want to obtain the 6 bit (values between 0 and 63] equivalents:

[19 22 61  46 25  6  5 57]

Is there a way to do so without looping through the list and manually changing them accordingly?

Thanks!

okstef
  • 11
  • 4

2 Answers2

0

Just use mask like in c:

a & 63

You can also shift the number to get 6 higher bits:

a >> 2 & 63

Simple way:

translate_dict = {
    'A': 0, 'Q': 16, 'g': 32, 'w': 48,
    'B': 1, 'R': 17, 'h': 33, 'x': 49,
    'C': 2, 'S': 18, 'i': 34, 'y': 50,
    'D': 3, 'T': 19, 'j': 35, 'z': 51,
    'E': 4, 'U': 20, 'k': 36, '0': 52,
    'F': 5, 'V': 21, 'l': 37, '1': 53,
    'G': 6, 'W': 22, 'm': 38, '2': 54,
    'H': 7, 'X': 23, 'n': 39, '3': 55,
    'I': 8, 'Y': 24, 'o': 40, '4': 56,
    'J': 9, 'Z': 25, 'p': 41, '5': 57,
    'K': 10, 'a': 26, 'q': 42, '6': 58,
    'L': 11, 'b': 27, 'r': 43, '7': 59,
    'M': 12, 'c': 28, 's': 44, '8': 60,
    'N': 13, 'd': 29, 't': 45, '9': 61,
    'O': 14, 'e': 30, 'u': 46, '+': 62,
    'P': 15, 'f': 31, 'v': 47, '/': 63
}

print([translate_dict[sym] for sym in 'TW9uZGF5'])
ADR
  • 1,255
  • 9
  • 20
  • when I do that, it results in: [20 23 57 53 26 7 6 53] but I want something like: [19 22 61 46 25 6 5 57] which is according to this table (https://en.wikipedia.org/wiki/Base64) – okstef Apr 02 '17 at 02:10
  • Why 84 -> 19?? `bin(84) -> '0b1010100'`, `bin(19) -> '0b10011'` – ADR Apr 02 '17 at 02:13
  • Because that is the appropriate 6 bit value for 'T', according to the Base64 index table found in the link in my previous comment. – okstef Apr 02 '17 at 02:19
  • That will work for the uppercase letters, but unfortunately not for the rest because in ASCII there are characters between the uppercase, lowercase, and numbers, but for Base 64 it is simply 0:25 = uppercase, 26:51 = lowercase, 52:63 = 0:9 and '+' and '/' – okstef Apr 02 '17 at 02:23
0

Your question is tagged Python 3.x, but you can't pass a string to base64.b64encode in Python 3.x (need to pass bytes instead). Anyway, this shows how to do this on either version, but it's not particularly optimized for either one:

import base64


codes = list(range(ord('A'), ord('Z')+1))
codes += list(range(ord('a'), ord('z')+1))
codes += list(range(ord('0'), ord('9')+1))
codes.extend((ord('+'), ord('/')))

remap = dict(zip(codes, range(64)))

print([remap[x] for x in bytearray(base64.b64encode(b'Monday'))])
Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42