Packing int and float to byte arrays in Julia

3.3k views Asked by At

I am trying to find out how I can pack an integer or float value in to a byte array in Julia. In Python I would just do the following:

struct.pack("<q",1)

Which would give me '\x01\x00\x00\x00\x00\x00\x00\x00'

or for a float:

struct.pack("<f",0.1)

Is there any package in Julia that provides this?

Thanks!

3

There are 3 answers

1
StefanKarpinski On

See the StrPack package: https://strpackjl.readthedocs.org/en/latest/

This is actually one of the oldest Julia packages around.

1
rickhg12hs On

A couple other options to StrPack.jl:

julia> function num2byteA{T<:Union(Float16, Float32, Float64, Signed, Unsigned)}(x::T)
           iob = IOBuffer()
           write(iob, x)
           seekstart(iob)
           return readbytes(iob)
       end
num2byteA (generic function with 1 method)

julia> num2byteA(31)
4-element Array{UInt8,1}:
 0x1f
 0x00
 0x00
 0x00

julia> num2byteA(31.5)
8-element Array{UInt8,1}:
 0x00
 0x00
 0x00
 0x00
 0x00
 0x80
 0x3f
 0x40

You can play with fire a bit and read/convert straight from memory:

julia> function any2byteA(x)
           sz = sizeof(x)
           ba = Vector{UInt8}(sz)
           src_ptr = convert(Ptr{UInt8}, pointer_from_objref(x))
           unsafe_copy!(pointer(ba), src_ptr, sz)
           return ba
       end
any2byteA (generic function with 1 method)

julia> any2byteA(31.5)
8-element Array{UInt8,1}:
 0x00
 0x00
 0x00
 0x00
 0x00
 0x80
 0x3f
 0x40

julia> type MyType
         a::Int32
         b::Float64
       end

julia> a=MyType(511,127.125)
MyType(511,127.125)

julia> any2byteA(a)
12-element Array{UInt8,1}:
 0xff
 0x01
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0xc8
 0x5f
 0x40
0
JobJob On

To get a byte array of x:

reinterpret(UInt8, [x])

Examples:

julia> reinterpret(UInt8, [12])
8-element reinterpret(UInt8, ::Vector{Int64}):
 0x0c
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
julia> reinterpret(UInt8, [1.0, 333.0])
16-element reinterpret(UInt8, ::Vector{Float64}):
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0xf0
 0x3f
 0x00
 0x00
 0x00
 0x00
 0x00
 0xd0
 0x74
 0x40