简体   繁体   English

如何将字符串中的原始ascii值转换为整数?

[英]How do I convert raw ascii values in string to integer?

I have a 128 bit value I'm storing as a string in python. 我有一个128位值,要以字符串形式存储在python中。 I would like to retrieve the last 4 bytes of it, increment it, and then put it back into the 128 bit value. 我想检索它的最后4个字节,将其递增,然后将其放回128位值。 Example: 例:

mybigvalue = "69dda8455c7dd4254bf353b773304eec".decode('hex')
lastInt = mybigvalue [12:]
lastInt =lastInt +1
mybigvalue [12:] = lastInt

This doesn't work though. 但是,这不起作用。 I'm a python noob and not sure what to try next, or if my entire idea of doing this is wrong. 我是python noob,不确定下一步要尝试什么,或者不确定执行此操作的整个想法是否错误。 I come from a C background and do not totally understand how python treats data. 我来自C语言,并不完全了解python如何处理数据。

Python 2: use struct.unpack() to interpret those last 4 bytes as an integer: Python 2:使用struct.unpack()将最后4个字节解释为整数:

import struct

lastInt = struct.unpack('<I', mybigvalue[-4:])[0]
lastInt += 1
mybigvalue = mybigvalue[:-4] + struct.pack('<I', lastInt & ((1 << 32) - 1))

'<I' means the bytes are interpreted as an unsigned integer, little-endian. '<I'表示字节被解释为无符号整数little-endian。

I also masked the value to fit within 32 bits; 我还屏蔽了该值以使其适合32位; ffffffff will overflow to 00000000 that way. ffffffff将以这种方式溢出到00000000

Demo: 演示:

>>> import struct
>>> mybigvalue = "69dda8455c7dd4254bf353b773304eec".decode('hex')
>>> lastInt = struct.unpack('<I', mybigvalue[-4:])[0]
>>> lastInt += 1
>>> mybigvalue = mybigvalue[:-4] + struct.pack('<I', lastInt & ((1 << 32) - 1))
>>> print mybigvalue.encode('hex')
69dda8455c7dd4254bf353b774304eec

The 73304eec incremented to 74304eec ; 73304eec增加到74304eec if you wanted 73304eed instead, use big-endian; 如果要73304eed ,请使用big-endian。 '>I' . '>I'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM