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 |
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))
In [12]:
import array
import pprint
a = array.array('i', range(3))
print('initialize\n', a)
In [13]:
a.extend(range(3))
print('Extend\n',a)
In [14]:
print('Slice \n', a[2:5])
In [15]:
print('Iterartor\n')
print(list(enumerate(a)))
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)
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))