We can do this to turn an array of UInt8
into UInt64
reinterpret(UInt64, rand(UInt8, 8))
is there an inverse of this? To turn UInt64
into Vector{UInt8}
?
Just reinterpret again. Remember reinterpret makes something that acts like an array, even if it is length 1.
julia> a8 = rand(UInt8, 8)
8-element Array{UInt8,1}:
0x25
0xaf
0x2c
0x33
0xca
0xbe
0xd8
0xa6
julia> a64 = reinterpret(UInt64, a8)
1-element reinterpret(UInt64, ::Array{UInt8,1}):
0xa6d8beca332caf25
julia> a8 = reinterpret(UInt8, a64)
8-element reinterpret(UInt8, reinterpret(UInt64, ::Array{UInt8,1})):
0x25
0xaf
0x2c
0x33
0xca
0xbe
0xd8
0xa6
It's worth noting that reinterpret
works in two different ways. One is to reinterpret a primitive type as another primitive type, as in reinterpret(Char, 0x00000077)
. Another is to reinterpret an array of type T as an array of another type, as in reinterpret(UInt128, [1, 2])
. In both cases, these two operations don't involve actually changing or copying the data.
If you are asking how to turn an bitstype (like UInt64) into an array, that is different, because you actually need to allocate an array, thereby copying the data. So you are not "reinterpreting" existing data, but creating new.
You can do this using a pointer:
function to_array(x::UInt64)
arr = Vector{UInt8}(undef, 8)
GC.@preserve arr unsafe_store!(Ptr{UInt64}(pointer(arr)), x)
return arr
end
This is highly efficient. But again, this is not a reinterpret operation at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With