# Reinterpret packed data which is already in memory?

**URL:** <https://discourse.julialang.org/t/reinterpret-packed-data-which-is-already-in-memory/39549>\
**Category:** General Usage\
**Created:** [May 15, 2020, 6:47pm UTC](https://discourse.julialang.org/t/reinterpret-packed-data-which-is-already-in-memory/39549 "2020-05-15T18:47:37Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 15, 2020, 7:07pm UTC](https://discourse.julialang.org/t/reinterpret-packed-data-which-is-already-in-memory/39549/2 "2020-05-15T19:07:46Z")

</div>

> [@tamasgal](#):
>
> Am I hitting the wall here or is there some (dirty) way to create an actual structure in Julia which I can map over my in-memory data?

You can use `primitive` types.

```julia
# define a type that acts like a "packed" 24-bit struct of x::UInt8, y::UInt16:
primitive type Foo 24 end

function Base.getproperty(foo::Foo, s::Symbol)
    # create a Ref so that we can get a pointer to the raw bytes;
    # I'm not sure if there is a nicer way (unless the primitive type has
    # the right size to be be reinterpreted as a UInt64 or similar)
    r = Ref(foo)
    GC.@preserve r begin
        if s === :x
            return unsafe_load(Ptr{UInt8}(Base.unsafe_convert(Ptr{Cvoid}, r)))
        elseif s === :y
            return unsafe_load(Ptr{UInt16}(Base.unsafe_convert(Ptr{Cvoid}, r)+1))
        end
    end
    error("unknown field $s")
end
Base.show(io::IO, foo::Foo) = print(io, "Foo(", foo.x, ',', foo.y, ')')

```

after which you can do:

```julia
julia> foodata = reinterpret(Foo, [0x01, 0x00, 0x10, 0x02, 0x00, 0x20])
2-element reinterpret(Foo, ::Array{UInt8,1}):
 Foo(1,4096)
 Foo(2,8192)

julia> foodata[2].y
0x2000

```

---

_[View the full topic](https://discourse.julialang.org/t/reinterpret-packed-data-which-is-already-in-memory/39549)._
