0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

基本情報技術者試験 科目B base64のエンコード処理

Last updated at Posted at 2023-09-13

大滝みや子さんのアルゴリズム×擬似言語トレーニングブックもだいぶ進んできました。

4章は難しくも解説を見れば大体わかるのですが、base64のエンコード処理は解説が端折ってあったため、いまいち動きがわかりません。

pythonのコードで動かしてみたらだいぶわかりましたので、共有します。

いやあめんどくさい・・・試験ででないといいな・・・
というか使うときは来るのか?

コード:

# エンコード対象の文字列
encode = ['H', 'e', 'l', '']

# 各文字をASCIIの整数値に変換
data = [ord(char) for char in encode[:-1]]

print("初期状態:")
for i in range(3):
    print(f"data[{i + 1}]: {data[i]:08b} ({data[i]})")
print("")

# 1. encode[0]にdata[1]の上位6ビットを取得(2ビット右)
encode[0] = (data[0] >> 2) & 0b111111
print("1の処理後:")
print(f"encode[0]: {encode[0]:06b} ({encode[0]})")
print("")

# 2. encode[1]にdata[1]の下位2ビット(4ビット左)と、
#data[2]の上位4ビット(4ビット右)を結合
encode[1] = ((data[0] & 0b11) << 4) | ((data[1] >> 4) & 0b1111)
print("2の処理後:")
print(f"encode[1]: {encode[1]:06b} ({encode[1]})")
print("")

# 3. encode[2]にdata[2]の下位4ビット(2ビット左)と、data[3]の上位2ビット(6ビット右)を結合
encode[2] = ((data[1] & 0b1111) << 2) | ((data[2] >> 6) & 0b11)
print("3の処理後:")
print(f"encode[2]: {encode[2]:06b} ({encode[2]})")
print("")

# 4. encode[3]にdata[3]の下位6ビットを取得
encode[3] = data[2] & 0b111111
print("4の処理後:")
print(f"encode[3]: {encode[3]:06b} ({encode[3]})")

# 結果のエンコードされた文字列を表示
encoded_string = ' '.join([f"{item:06b}" for item in encode])
print("\nエンコードされた結果:")
print(encoded_string)

結果:

初期状態:
data[1]: 01001000
data[2]: 01100101
data[3]: 01101100

1の処理後:
encode[0]: 010010

2の処理後:
encode[1]: 000110

3の処理後:
encode[2]: 010101

4の処理後:
encode[3]: 101100

エンコードされた結果:
010010 000110 010101 101100
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?