Skip to content

Commit 8966aa2

Browse files
author
Chaluvadi
committed
Added common examples
1 parent fecdb91 commit 8966aa2

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

examples/common/idxio.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env python
2+
3+
#######################################################
4+
# Copyright (c) 2024, ArrayFire
5+
# All rights reserved.
6+
#
7+
# This file is distributed under 3-clause BSD license.
8+
# The complete license agreement can be obtained at:
9+
# http://arrayfire.com/licenses/BSD-3-Clause
10+
########################################################
11+
12+
def reverse_char(b):
13+
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4
14+
b = (b & 0xCC) >> 2 | (b & 0x33) << 2
15+
b = (b & 0xAA) >> 1 | (b & 0x55) << 1
16+
return b
17+
18+
19+
# http://stackoverflow.com/a/9144870/2192361
20+
def reverse(x):
21+
x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1)
22+
x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2)
23+
x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4)
24+
x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8)
25+
x = ((x >> 16) & 0xffff) | ((x & 0xffff) << 16);
26+
return x
27+
28+
29+
def read_idx(name):
30+
with open(name, 'rb') as f:
31+
# In the C++ version, bytes the size of 4 chars are being read
32+
# May not work properly in machines where a char is not 1 byte
33+
bytes_read = f.read(4)
34+
bytes_read = bytearray(bytes_read)
35+
36+
if bytes_read[2] != 8:
37+
raise RuntimeError('Unsupported data type')
38+
39+
numdims = bytes_read[3]
40+
elemsize = 1
41+
42+
# Read the dimensions
43+
elem = 1
44+
dims = [0] * numdims
45+
for i in range(numdims):
46+
bytes_read = bytearray(f.read(4))
47+
48+
# Big endian to little endian
49+
for j in range(4):
50+
bytes_read[j] = reverse_char(bytes_read[j])
51+
bytes_read_int = int.from_bytes(bytes_read, 'little')
52+
dim = reverse(bytes_read_int)
53+
54+
elem = elem * dim;
55+
dims[i] = dim;
56+
57+
# Read the data
58+
cdata = f.read(elem * elemsize)
59+
cdata = list(cdata)
60+
data = [float(cdata_elem) for cdata_elem in cdata]
61+
62+
return (dims, data)
63+
64+
if __name__ == '__main__':
65+
# Example usage of reverse_char
66+
byte_value = 0b10101010
67+
reversed_byte = reverse_char(byte_value)
68+
print(f"Original byte: {byte_value:08b}, Reversed byte: {reversed_byte:08b}")
69+
70+
# Example usage of reverse
71+
int_value = 0x12345678
72+
reversed_int = reverse(int_value)
73+
print(f"Original int: {int_value:032b}, Reversed int: {reversed_int:032b}")

0 commit comments

Comments
 (0)