【问题标题】:Converting data from ASCII to Base 64 without an encoder in Python在 Python 中不使用编码器将数据从 ASCII 转换为 Base 64
【发布时间】:2015-02-06 03:57:48
【问题描述】:

我正在尝试创建两个程序,一个将数据从 ASCII -> 整数转换为 -> Base 64,另一个将过程反转,以测试如何使用以下示例执行此操作,其中我输入“Cat”并出现最高为 0b10001000110111101100111。但是我无法将它转移到 Base 64,我最终应该使用 RG9N,我不确定我应该添加什么来解决这个问题,我是 Python 和一般编程的新手。

Base 64 编码器

打包成整数

number = ord('C')
number = ord('a') + (number << 8)
number = ord('t') + (number << 8)

print(bin(number))

#Base64 from integer

code = number  >> (6 * 3)
number = number - (code  << (6 * 3))
code = number >> (6 * 2)
number = number - (code  << (6 * 3))
code = number >> (6 * 1)
number = number - (code << (6 * 1))

print(chr(code))

【问题讨论】:

  • 你可以看看它是如何在 Python 的标准库中实现的。请参阅base64.py 文件。

标签: python python-3.x base64 ascii


【解决方案1】:

首先,您需要 4 个打印语句,而不仅仅是一个 - 您创建的 4 个代码中的每一个都必须输出。您可能还更喜欢write 而不是print,因为print 将为每个输出添加一个空格。

其次,您不能只对这些代码调用chr,因为它们会转换为不可打印的字符。您需要从代码编号到字符的映射,您可以在 Wikipedia 找到它。

您使用的将 3 个输入字符转换为 4 个输出字符的基本方法是声音。但是您还需要在序列末尾的一些特殊情况代码,其中剩余的字符少于 3 个,并且您需要在输出中插入 = 填充。

【讨论】:

  • 这很有道理,谢谢,尽管我不确定如何实现代码到字符的映射。它看起来像 if 0
  • @ShahobMousavi 最简单的方法是创建一个列表,然后将其编入索引。
猜你喜欢
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2014-02-26
相关资源
最近更新 更多