|
| 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 | + |
| 13 | +def reverse_char(b): |
| 14 | + b = (b & 0xF0) >> 4 | (b & 0x0F) << 4 |
| 15 | + b = (b & 0xCC) >> 2 | (b & 0x33) << 2 |
| 16 | + b = (b & 0xAA) >> 1 | (b & 0x55) << 1 |
| 17 | + return b |
| 18 | + |
| 19 | + |
| 20 | +# http://stackoverflow.com/a/9144870/2192361 |
| 21 | +def reverse(x): |
| 22 | + x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1) |
| 23 | + x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2) |
| 24 | + x = ((x >> 4) & 0x0F0F0F0F) | ((x & 0x0F0F0F0F) << 4) |
| 25 | + x = ((x >> 8) & 0x00FF00FF) | ((x & 0x00FF00FF) << 8) |
| 26 | + x = ((x >> 16) & 0xFFFF) | ((x & 0xFFFF) << 16) |
| 27 | + return x |
| 28 | + |
| 29 | + |
| 30 | +def read_idx(name): |
| 31 | + with open(name, "rb") as f: |
| 32 | + # In the C++ version, bytes the size of 4 chars are being read |
| 33 | + # May not work properly in machines where a char is not 1 byte |
| 34 | + bytes_read = f.read(4) |
| 35 | + bytes_read = bytearray(bytes_read) |
| 36 | + |
| 37 | + if bytes_read[2] != 8: |
| 38 | + raise RuntimeError("Unsupported data type") |
| 39 | + |
| 40 | + numdims = bytes_read[3] |
| 41 | + elemsize = 1 |
| 42 | + |
| 43 | + # Read the dimensions |
| 44 | + elem = 1 |
| 45 | + dims = [0] * numdims |
| 46 | + for i in range(numdims): |
| 47 | + bytes_read = bytearray(f.read(4)) |
| 48 | + |
| 49 | + # Big endian to little endian |
| 50 | + for j in range(4): |
| 51 | + bytes_read[j] = reverse_char(bytes_read[j]) |
| 52 | + bytes_read_int = int.from_bytes(bytes_read, "little") |
| 53 | + dim = reverse(bytes_read_int) |
| 54 | + |
| 55 | + elem = elem * dim |
| 56 | + dims[i] = dim |
| 57 | + |
| 58 | + # Read the data |
| 59 | + cdata = f.read(elem * elemsize) |
| 60 | + cdata = list(cdata) |
| 61 | + data = [float(cdata_elem) for cdata_elem in cdata] |
| 62 | + |
| 63 | + return (dims, data) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + # Example usage of reverse_char |
| 68 | + byte_value = 0b10101010 |
| 69 | + reversed_byte = reverse_char(byte_value) |
| 70 | + print(f"Original byte: {byte_value:08b}, Reversed byte: {reversed_byte:08b}") |
| 71 | + |
| 72 | + # Example usage of reverse |
| 73 | + int_value = 0x12345678 |
| 74 | + reversed_int = reverse(int_value) |
| 75 | + print(f"Original int: {int_value:032b}, Reversed int: {reversed_int:032b}") |
0 commit comments