python3中bytes、hex和字符串相互转换
2024-08-30 00:46:41
1、字符串转bytes
a = 'abcd'
a1 = bytes(a,encoding('utf-8'))
2、bytes转字符串
a = b'abcd'
a1 = bytes.decode(a , encoding('utf-8'))
3、16进制字符串转bytes
a='01 02 03 04 05 06'
a1 = a.replace(' ' ,'')
a2 = bytes,fromhex(a1)
4、bytes转16进制字符串
"".join(['%02X ' % b for b in bs])
5、byte和int相互转换
b = b'\x12\x34'
n = int.from_bytes(b,byteorder='big',signed=False)
#b'\x12\x34'->4660 n = 4660
b = n.to_bytes(length=2,byteorder='big',signed=False)
#4660->b'\x12\x34'
6、字节数组bytearray
1) 可变的字节序列,相当于bytes的可变版本
2) 创建bytearray对象的方法规则
bytearray()
bytearray(整数n)
bytearray(整型可迭代对象)
bytearray(b'字符串')
bytearray(字符串, encoding='utf-8')
示例:
>>> bytearray()
bytearray(b'') >>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03') >>> bytearray(["a","b","c"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required >>> bytearray(3)
bytearray(b'\x00\x00\x00') >>> bytearray("abc",encoding="utf-8")
bytearray(b'abc') >>> bytearray("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
最新文章
- 定制Eclipse IDE之界面篇
- VS 远程发布IIS
- Linux命令入门
- 1.1Linux 系统简介(学习过程)
- Java基础-ArrayList和LinkedList的区别
- div滚动条演示
- JavaWeb之Servlet: ServletConfig 与 ServletContext
- Android模拟器分辨率介绍
- C# 解决DrawImage绘制图片拉伸产生渐变
- (五)unity4.6Ugui中文教程文档-------概要-UGUI Interaction Components
- hdu3714 三分
- FileAttributes枚举
- LINQ To XML的一些方法
- mysql、oracle和SQL server数据库的区别
- 使用测试思路快速学习Python-适合测试工程师的学习方法
- Git上传代码的步骤
- 【Luogu4396】[AHOI2013]作业(莫队)
- js 原生 ajax
- JSON: jasckson 字段 过滤
- VS2010带不出System.Data.OracleClient这个引用的解决方案
热门文章
- E20180607-hm
- 719. Find K-th Smallest Pair Distance
- HDU3433 【时间的二分+DP最优解】
- 走进VR游戏开发的世界
- [Xcode 实际操作]九、实用进阶-(1)隐藏顶部的状态栏
- Mol Cell Proteomics. |廖文丽| 阿尔兹海默症临床前期的脑脊液中突触蛋白的变化先于神经变性标志物
- 请写出JAVA弹栈压栈的步骤, 栈的存储方式
- mysql之SQL入门与提升(四)——终结篇,函数
- 第二篇 HTML5打包发布IOS APP之苹果开发者账号申请流程
- 世风日下的哗啦啦族I (简单分块模板)