Reference a byte array as an integer

核能气质少年 提交于 2019-12-25 03:22:37

问题


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.

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;
}

The above program prints 60. I am looking for a way to do this in Python.


回答1:


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


来源:https://stackoverflow.com/questions/53937652/reference-a-byte-array-as-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!