【问题标题】:Bytes to Int conversion in Python 3Python 3 中的字节到 Int 转换
【发布时间】:2020-04-21 19:12:42
【问题描述】:

我有一个名为 offset 的变量属于 <class 'bytes'>

我需要找到b/w offset和mapper[hash]的区别,这里mapper[hash]属于<class 'numpy.int64'>

我的功能如下:

for hash, sid, offset in x:
     yield(sid, int(offset) - mapper[hash])

注意:在原始函数中,偏移量没有被强制转换为 int。我故意这样做是为了让他们与众不同。

但这是抛出一个错误说

ValueError: invalid literal for int() with base 10: b'\xf9\x01\x00\x00\x00\x00\x00\x00'

并不奇怪,虽然在调试时我打印了偏移量而不进行类型转换并找到了值 ->

b'\xcb\x10\x00\x00\x00\x00\x00\x00'
b'B\x10\x00\x00\x00\x00\x00\x00'
b'T\x1c\x00\x00\x00\x00\x00\x00'

这个问题有哪些可能的解决方案。

【问题讨论】:

    标签: numpy type-conversion python-3.6 literals hashlib


    【解决方案1】:

    这些值看起来合理吗?

    In [292]: alist = [b'\xcb\x10\x00\x00\x00\x00\x00\x00', 
         ...: b'B\x10\x00\x00\x00\x00\x00\x00', 
         ...: b'T\x1c\x00\x00\x00\x00\x00\x00']                                                            
    In [293]: [np.frombuffer(astr,int) for astr in alist]                                                  
    Out[293]: [array([4299]), array([4162]), array([7252])]
    

    看起来每个字节串是 8 个字节,所以可能是 int64 对象的字节表示。

    【讨论】:

    • for hash, sid, offset in x: val = (np.frombuffer(offset,int)) yield (sid, val[0] - mapper[hash]) 可以吗,幸好我是没有收到任何错误!
    猜你喜欢
    • 2014-01-27
    • 2021-09-14
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多