1. str2hex_hex2str
1.1. python 实现 hex2str, str2hex
python 实现字符串和16进制字符串相互转换
import sys
def str2hex(input_data: str) -> str:
"""将字符串转换为十六进制表示"""
byte_data = input_data.encode('utf-8')
return byte_data.hex()
def hex2str(hex_string: str) -> str:
"""将十六进制字符串转换回原始字符串"""
try:
byte_data = bytes.fromhex(hex_string)
return byte_data.decode('utf-8')
except ValueError as e:
print(f"错误: 无效的十六进制字符串 - {
e}")
return None
# python str2hex.py str1 str2
if __name__ == "__main__":
if "68656c6c6f" == str2hex("hello"):
print("hello hex is 68656c6c6f")
for i in range(len(sys.argv)-1):
hex = str2hex(sys.argv[i+1])
str_data = hex2str(hex)
print(str_data, hex)
python str2hex.py str1 str2
hello hex is 68656c6c6f
str1 73747231
str2 73747232
1.2. C 实现 hex2str, str2hex
#include <ctype.h>
#include <stdio.h>
#include <string.h>
// 将字符串转换为十六进制字符串,返回实际转换的字节数(成功)或 -1(失败)
int str2hex(char *hex, unsigned int hex_len, unsigned char *str, unsigned int str_len) {
int i;
if (str_len * 2 > hex_len - 1) {
printf("dst buf is not enough! Need %u bytes, but only %u available.\n", str_len * 2 + 1, hex_len);
return -1;
}
for (i = 0; i <

本文介绍了两个Python函数str2hex和hex2str,用于将字符串转换为十六进制和从十六进制还原回字符串,展示了如何在命令行中使用这些工具进行数据转换。
最低0.47元/天 解锁文章
985

被折叠的 条评论
为什么被折叠?



