Packing int and float to byte arrays in Julia
Asked Answered
Z

3

2

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!

Zambia answered 10/6, 2015 at 20:28 Comment(4)
When you write "byte array", do you mean Array{UInt8,1} or ASCIIString?Curative
I ment Array{Uint8, 1}. The StrPack provides what I need, thxZambia
StrPack does not work with v0.4. However, one can easily fix it by replacing all T.names with fieldnames(T) in the module source.Bombycid
It is actually just fixed for 0.4Zambia
T
2

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

This is actually one of the oldest Julia packages around.

Thule answered 10/6, 2015 at 20:56 Comment(1)
Thanks! This indeed does what I need.Zambia
U
2

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
Usufruct answered 3/3, 2022 at 11:15 Comment(0)
C
1

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
Curative answered 12/6, 2015 at 3:58 Comment(1)
or shorter any2byteA(x) = reinterpret(UInt8, [x]).Duenas

© 2022 - 2024 — McMap. All rights reserved.