Closed francois-baptiste closed 1 year ago
Sorry @giancastro @brendancol , I have to reopen this.
Even if the addition of np.ascontiguousarray
add an extra security check it doesn't make the code platform agnostic
In [1]: np.ascontiguousarray(np.array([3735928559],dtype=np.uint32)).tobytes()
Out[1]: b'\xef\xbe\xad\xde' #machine is little-endian
In [2]: np.ascontiguousarray(np.array([3735928559],dtype=np.uint32)).tobytes()
Out[2]: b'\xde\xad\xbe\xef' #machine is big-endian
@giancastro Here is the code I was thinking of: It should work, even if a bit complex to test endianness agnosticism.
import sys
should_swap = {"=": sys.byteorder == "little", "<": True, ">": False, "|": False}
arr = np.array([3735928559], dtype="<i4")
#arr = np.array([3735928559], dtype='>i4')
#arr = np.array([3735928559], dtype=np.int32)
if should_swap[arr.dtype.byteorder]:
print(np.ascontiguousarray(arr.byteswap()).tobytes())
else:
print(np.ascontiguousarray(arr).tobytes())
I think the call to numpy .tobytes() need some rework as it doesn't seems endian agnostic (and thus not platform agnostic).
It seems I used
little-endian
the default endianness of my machine but it seembig-endian
is the norm, at least in this Wikipedia page https://en.wikipedia.org/wiki/Deadbeef.