Skip to content

Instantly share code, notes, and snippets.

@cress-cc
Last active May 22, 2019 01:11
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 cress-cc/985dc5923686e21f19ee14a57129ade4 to your computer and use it in GitHub Desktop.
Save cress-cc/985dc5923686e21f19ee14a57129ade4 to your computer and use it in GitHub Desktop.
復活の呪文
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import sys
class FukkatsuEncoder:
__USABLE_CHARS = \
'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほ' \
'まみむめもらりるれろがぎぐげござじずぜぞばびぶべぼぱぴぷぺぽ' \
'やゆよわ'
def encode(self, raw: bytes) -> str:
b = ''.join(map(lambda c: format(c, '08b'), raw))
# 6の倍数になるようゼロ埋めする
b += '00000'
b = b[0:-(len(b)%6)]
# 連番が偶数となる要素は空文字なので除外する
encoded = ''.join(map(lambda c: self.__USABLE_CHARS[int(c, 2)], \
re.split('(.{6})', b)[1::2] \
))
return encoded
def decode(self, encoded: str) -> bytes:
b = ''.join(map(lambda c: format(self.__USABLE_CHARS.find(c), '06b'), \
encoded))
# 8の倍数に満たない場合、末尾は捨てられてしまうので問題なし
raw = bytes(map(lambda i: int(i, 2), \
re.split('(.{8})', b)[1::2]))
return raw
def main():
fe = FukkatsuEncoder()
print(fe.encode('あいう'.encode()))
# => ぴぴきうぴぴきおぴぴきき
print(fe.decode('ぴぴきうぴぴきおぴぴきき').decode())
# => あいう
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment