Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: What's the inverse (opposite) of reinterpret?

Tags:

julia

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}?

like image 681
xiaodai Avatar asked Dec 06 '22 09:12

xiaodai


2 Answers

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
like image 133
Bill Avatar answered Dec 07 '22 21:12

Bill


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.

like image 31
Jakob Nissen Avatar answered Dec 07 '22 23:12

Jakob Nissen