Memcpy in julia

Hi everyone
I have a vector which contains 5 uint8 elements. How do I copy them to two int32 variables ? we can do it with memcpy in c. Is there similar command in julia?

x=[0x3 0x00  0x11 0x00 0x80]
m= convert(Int32, signed(x[3])&0x0f)<<16 | convert( Int32, signed(x[2]))<<8 | convert( Int32, signed(x[1]));
n= convert(Int32, signed(x[5]))<<16 |convert(Int32, signed(x[4]))<<8 | convert (Int32, signed(x[3])>>4);

This code is run but it isn’t optimal. Is there other way? Thanks alot.

Use reinterpret.

1 Like

I see now that you’ve edited your question (which was about 4 UInt8 instead of 5).

If you show code, please surround it in triple backticks (```) to make it easier to read & follow, and ultimately to make it easier to help you.

I’m not sure using memcpy to interpret 5 bytes as two Int32 works in C either - you’ll interpret bytes outside of the array as part of the last Int32, which is a dangerous thing (and probably undefined behavior as well). Where do you get those bytes from? What do you want to do with them?

Assuming you want to have the top 3 bytes to be 0x00, you can just

while length(x) % 4 != 0
  push!(x, zero(UInt8))

(or calculate the new size statically and append! the correct amount directly) and then do reinterpret(Int32, x).

I recieve data from udp network. Each 20 bits is a variable. How do I spilit data?

With bit shifts, something along the lines of your original post.

1 Like