Python byte转integer/string

栏目: Python · 发布时间: 6年前

内容简介:需求:将形如方法1 导入方法2

需求:将形如 ’y\xcc\xa6\xbb’byte 字符串转化为 integer 或者 string

方法1 导入 struct

import struct
struct.unpack("<L", "y\xcc\xa6\xbb")[0]

方法2 python3.2 及以上

byte 串采取大端法:

int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')

若采取小端法,则:

int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')

方法3 借助十六进制转换

大端法:

s = 'y\xcc\xa6\xbb' 
num = int(s.encode('hex'), 16)

小端法:

int(''.join(reversed(s)).encode('hex'), 16)

方法4 使用 array

import array 
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]

其中 I 用于表示大端或小端,且使用此方法要注意自己使用的 python 版本。

方法5 自己写函数实现

如:

sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))

又如:

def bytes2int( tb, order='big'):
    if order == 'big': seq=[0,1,2,3]
    elif order == 'little': seq=[3,2,1,0]
    i = 0
    for j in seq: i = (i<<8)+tb[j]
    return i

字符数组转换成字符串

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring() 
'\x11\x18y\x01\x0c\xde"L'

参考链接


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mastering Regular Expressions, Second Edition

Mastering Regular Expressions, Second Edition

Jeffrey E F Friedl / O'Reilly Media / 2002-07-15 / USD 39.95

Regular expressions are an extremely powerful tool for manipulating text and data. They have spread like wildfire in recent years, now offered as standard features in Perl, Java, VB.NET and C# (and an......一起来看看 《Mastering Regular Expressions, Second Edition》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具