将字节数组引用为整数 [英] Reference a byte array as an integer
本文介绍了将字节数组引用为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我知道python 3中存在某些可以从现有字节数组创建新整数的方法。但是,我正在寻找一种创建对字节数组作为整数的引用的方法。这样,如果引用被更改,则基础字节数组也将更改。
In Python, I am aware certain methods exist in python 3 that can create a new integer from an existing byte array. However, I am looking for a way to create a reference to a byte array, as an integer. Such that, if the reference is changed, then the underlying byte array is also changed.
在C中,这将如下所示:
In C, this would be done like the following:
int main(void) {
unsigned char bytes[4] = {1, 0, 0, 0};
int* int_ref = (int*)bytes;
*int_ref += 59;
printf("bytes is now %u %u %u %u\n",
bytes[0],
bytes[1],
bytes[2],
bytes[3]);
return 0;
}
以上程序显示 60
。我正在寻找一种在Python中执行此操作的方法。
The above program prints 60
. I am looking for a way to do this in Python.
推荐答案
类似的东西似乎与您想要的东西相似:
Something along these lines seems close to what you want:
import _ctypes
def di(obj_id):
""" Reverse of id() function. """
# from https://stackoverflow.com/a/15012814/355230
return _ctypes.PyObj_FromPtr(obj_id)
def func(obj_id):
ba = di(obj_id)
ba[0] += 50
data = bytearray([1, 0, 0, 0])
func(id(data))
print('bytes is now {} {} {} {}'.format(*data)) # -> bytes is now 51 0 0 0
这篇关于将字节数组引用为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文