Packing int and float to byte arrays in Julia

2019-05-21 07:21发布

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!

2条回答
我只想做你的唯一
2楼-- · 2019-05-21 07:33

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

This is actually one of the oldest Julia packages around.

查看更多
爷的心禁止访问
3楼-- · 2019-05-21 07:38

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
查看更多
登录 后发表回答