How to get an Array{UInt8,1} from Unsigned without passing by String?

I’m trying to pack UInt to Array{UInt8,1} without going through String without much success.

From byte to UInt, I would just do

T = UInt32
x = rand(UInt8,sizeof(T))
4-element Array{UInt8,1}:
 0xd6
 ...
y = bswap(reinterpret(T, x)[1])
0xdd9571d6

Since reinterpret has an Array as output I though it would just work the other way around but no…

reverse!(reinterpret(UInt8, y))
ERROR: bitcast: argument size does not match size of target type

For now I’m doing as follows but wonder if there would be something more straight forward, without going through String type?

hex2bytes(string(y, base=16))
4-element Array{UInt8,1}:
 ...

Does the following address your issue?

julia> T = UInt32
UInt32

julia> x = rand(UInt8,sizeof(T))
4-element Array{UInt8,1}:
 0xbe
 0x98
 0x11
 0x52

julia> y = reverse(x)
4-element Array{UInt8,1}:
 0x52
 0x11
 0x98
 0xbe

Either of these seems to do what you want:

julia> reinterpret(UInt8, [bswap(y)])
4-element reinterpret(UInt8, ::Array{UInt32,1}):
 0xd6
 0x71
 0x95
 0xdd

julia> [(y>>24)%UInt8, (y>>16)%UInt8, (y>>8)%UInt8, y%UInt8]
4-element Array{UInt8,1}:
 0xd6
 0x71
 0x95
 0xdd
1 Like

Exactly what I was looking for, thanks :slight_smile:

That would not work as I needed to go through the stage were y = 0x521198be and translate it back to x