Type code for array

code type minimum size
b int 1
B int 1
h signed int 2
H unsigned int 2
i sign int 2
I unsigned int 2
l signed long 4
L unsigned long 4
q signed long long 8
Q unsigned long long 8
f float 4
d double float 8

Initilization


In [7]:
import array
import binascii
s= b'this is a array'
a = array.array('b', s)
print('As byte string', s)
print('As array ', a)
print('As hex', binascii.hexlify(a))


As byte string b'this is a array'
As array  array('b', [116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 97, 114, 114, 97, 121])
As hex b'746869732069732061206172726179'

Manuipulating Arrays


In [12]:
import array
import pprint
a = array.array('i', range(3))
print('initialize\n', a)


initialize
 array('i', [0, 1, 2])

In [13]:
a.extend(range(3))
print('Extend\n',a)


Extend
 array('i', [0, 1, 2, 0, 1, 2])

In [14]:
print('Slice \n', a[2:5])


Slice 
 array('i', [2, 0, 1])

In [15]:
print('Iterartor\n')
print(list(enumerate(a)))


Iterartor

[(0, 0), (1, 1), (2, 2), (3, 0), (4, 1), (5, 2)]

Arrays and Files


In [16]:
import array
import binascii
import tempfile

a = array.array('i', range(5))
print('A1:', a)

# Write the array of numbers to a temporary file
output = tempfile.NamedTemporaryFile()
a.tofile(output.file)  # must pass an *actual* file
output.flush()

# Read the raw data
with open(output.name, 'rb') as input:
    raw_data = input.read()
    print('Raw Contents:', binascii.hexlify(raw_data))

    # Read the data into an array
    input.seek(0)
    a2 = array.array('i')
    a2.fromfile(input, len(a))
    print('A2:', a2)


A1: array('i', [0, 1, 2, 3, 4])
Raw Contents: b'0000000001000000020000000300000004000000'
A2: array('i', [0, 1, 2, 3, 4])

Alternative Byte Ordering


In [17]:
import array
import binascii


def to_hex(a):
    chars_per_item = a.itemsize * 2  # 2 hex digits
    hex_version = binascii.hexlify(a)
    num_chunks = len(hex_version) // chars_per_item
    for i in range(num_chunks):
        start = i * chars_per_item
        end = start + chars_per_item
        yield hex_version[start:end]


start = int('0x12345678', 16)
end = start + 5
a1 = array.array('i', range(start, end))
a2 = array.array('i', range(start, end))
a2.byteswap()

fmt = '{:>12} {:>12} {:>12} {:>12}'
print(fmt.format('A1 hex', 'A1', 'A2 hex', 'A2'))
print(fmt.format('-' * 12, '-' * 12, '-' * 12, '-' * 12))
fmt = '{!r:>12} {:12} {!r:>12} {:12}'
for values in zip(to_hex(a1), a1, to_hex(a2), a2):
    print(fmt.format(*values))


      A1 hex           A1       A2 hex           A2
------------ ------------ ------------ ------------
 b'78563412'    305419896  b'12345678'   2018915346
 b'79563412'    305419897  b'12345679'   2035692562
 b'7a563412'    305419898  b'1234567a'   2052469778
 b'7b563412'    305419899  b'1234567b'   2069246994
 b'7c563412'    305419900  b'1234567c'   2086024210