Packing int and float to byte arrays in Julia

为君一笑 提交于 2020-01-14 02:10:27

问题


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!


回答1:


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

This is actually one of the oldest Julia packages around.




回答2:


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


来源:https://stackoverflow.com/questions/30766680/packing-int-and-float-to-byte-arrays-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!