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
Array{UInt8,1}
orASCIIString
? – CurativeT.names
withfieldnames(T)
in the module source. – Bombycid