首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python中String, Bytes, Hex, Base64之间的关系与转换方法详解

Python中String, Bytes, Hex, Base64之间的关系与转换方法详解

作者头像
timerring
发布2022-07-20 14:37:12
发布2022-07-20 14:37:12
9170
举报
文章被收录于专栏:TechBlogTechBlog

Program : Type Hint, String, Bytes, Hex, Base64

In this program, you are required to learn basic concepts of Python 3.

Type hints is a feature to specify the type of a variable, which is useful for write correct codes. In all lab assignments, you are required to write Python 3 code with type hints feature. Recall that you are required to use at least Python 3.10, otherwise you might suffer from issues brings by type hints as PEP 563 has not become the default option until Python 3.10.

Your programs does the following:

In your readme.pdf file, apart from the general information, it should include:

  • A figure representing the relationship between all the variables in your program with type bytes and str. Example here:

The figure above is corresponding to the following code.

代码语言:javascript
复制
first_hex:str = input()
first_bytes:bytes = bytes.fromhex(first_hex)

solution code
代码语言:javascript
复制
import base64


def output_bytes(in_bytes: bytes):
    for ch in in_bytes:
        print(ch, end=' ')
    print()


def output_hex(in_bytes: bytes):
    for ch in in_bytes:
        print(hex(ch), end=' ')
    print()


def decode_utf8(in_bytes: bytes) -> str:
    return in_bytes.decode('utf-8')


print("Enter a string str1:")
str1: str = input()
byte_array: bytes = bytearray.fromhex(str1)
output_bytes(byte_array)
output_hex(byte_array)
encoded: bytes = base64.b64encode(byte_array)
print(encoded)
print("Enter a string str2:")
str2: str = input()
byte_array2: bytes = bytearray.fromhex(str2)
str3: str = decode_utf8(byte_array2)
print(str3)
  • output
代码语言:javascript
复制
Enter a string str1:
deadbeef
222 173 190 239 
0xde 0xad 0xbe 0xef 
b'3q2+7w=='
Enter a string str2:
4445414442454546
DEADBEEF

进程已结束,退出代码为 0
  • operating system version:WIN10
  • CPU instruction set:x64
  • Python interpreter version:Python3.9 A screenshot of the console output of the program

A figure representing the relationship between all the variables in your program with type bytes and str:

初学密码学,如果发现错误,还请各位指正。

受于文本原因,本文相关算法实现工程无法展示出来,现已将资源上传,可自行点击下方链接下载。

Python中String, Bytes, Hex, Base64之间的关系与转换方法详解工程文件

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Program : Type Hint, String, Bytes, Hex, Base64
    • solution code
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档