Skip to content

Instantly share code, notes, and snippets.

@CookieBox26
Created November 7, 2021 23:45
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 CookieBox26/9ea7b623c7f47d115935524bdaa7ea2b to your computer and use it in GitHub Desktop.
Save CookieBox26/9ea7b623c7f47d115935524bdaa7ea2b to your computer and use it in GitHub Desktop.
バイト列を Base64 文字列に変換
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@CookieBox26
Copy link
Author

以下のようにかく方がもっとコンパクトである。
前者はどこまでも大きい整数を扱うことになる。もっとも Python3 はどこまでも大きい整数を扱えるらしい。

mapping = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

def byteseq_to_base64str(byteseq):
    binstr = format(int(byteseq.hex(), 16), 'b')
    binstr = '0' * ((8 - len(binstr) % 8) % 8) + binstr
    binstr = binstr + '0' * ((6 - len(binstr) % 6) % 6)
    b64str = ''.join([mapping[int(binstr[i: i+6], 2)] for i in range(0, len(binstr), 6)])
    return b64str + '=' * ((4 - len(b64str) % 4) % 4)

def byteseq_to_base64str(byteseq):
    binstr = ''
    for b in byteseq:
        binstr += format(b, 'b').zfill(8)
    binstr = binstr + '0' * ((6 - len(binstr) % 6) % 6)
    b64str = ''.join([mapping[int(binstr[i: i+6], 2)] for i in range(0, len(binstr), 6)])
    return b64str + '=' * ((4 - len(b64str) % 4) % 4)

# 文字列を utf-8 エンコーディングでバイト列にしたもので確認
print(byteseq_to_base64str('abcdefg'.encode()))
print(byteseq_to_base64str('Dankeschön'.encode()))
print(byteseq_to_base64str('ありがとう'.encode()))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment