如何将一串字节转换为一个int? [英] How to convert a string of bytes into an int?

查看:147
本文介绍了如何将一串字节转换为一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中将字节字符串转换为int?

How can I convert a string of bytes into an int in python?

这样说:'y\xcc\xa6\xbb'

我想出了一种聪明/愚蠢的方法:

I came up with a clever/stupid way of doing it:

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

我知道必须有内置的东西或标准库中的东西可以更简单地完成此操作...

I know there has to be something builtin or in the standard library that does this more simply...

这与将字符串转换为十六进制数字不同您可以使用int(xxx,16),但我想转换为实际字节值的字符串.

This is different from converting a string of hex digits for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.

更新:

我有点喜欢James的回答,因为它不需要导入其他模块,但是Greg的方法更快:

I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:

>>> from timeit import Timer
>>> Timer('struct.unpack("<L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit()
0.36242198944091797
>>> Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit()
1.1432669162750244

我的骇客方法:

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

进一步更新:

有人在评论中询问导入另一个模块有什么问题.好吧,导入模块不一定便宜,请看一下:

Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:

>>> Timer("""import struct\nstruct.unpack(">L", "y\xcc\xa6\xbb")[0]""").timeit()
0.98822188377380371

包括导入模块的成本在内,几乎抵消了此方法的所有优点.我认为,这仅包括在整个基准测试运行中一次导入一次的费用;看一下我每次强制重新加载时会发生什么:

Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:

>>> Timer("""reload(struct)\nstruct.unpack(">L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit()
68.474128007888794

不用说,如果您每次导入都执行此方法很多次,则成比例地减少了一个问题.这也可能是I/O成本,而不是CPU,因此它可能取决于特定计算机的容量和负载特性.

Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.

推荐答案

您还可以使用 struct 模块执行此操作:

You can also use the struct module to do this:

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

这篇关于如何将一串字节转换为一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆