Josh Weinstein
Josh Weinstein

Reputation: 2968

Reference a byte array as an integer

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.

Upvotes: 0

Views: 183

Answers (1)

martineau
martineau

Reputation: 123413

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

Upvotes: 1

Related Questions