Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created December 18, 2019 06:08
Show Gist options
  • Save tk3369/101c2b630a49d1136365cc88c784999e to your computer and use it in GitHub Desktop.
Save tk3369/101c2b630a49d1136365cc88c784999e to your computer and use it in GitHub Desktop.

Suppose that we have an array of bytes that comes from a binary file. For simplicity sake, let's say we have just 8 64-bit integers loaded into memory, so we should have 64 bytes in the array.

Here's how we can generate a sample byte array:

julia> x = rand(1:100, 8)
8-element Array{Int64,1}:
  3
 49
 85
 45
 97
 36
 80
 82

julia> mem = collect(reinterpret(UInt8, x))
64-element Array{UInt8,1}:
 0x03
 0x00
 0x00
 0x00
    
 0x00
 0x00
 0x00
 0x00

To get the first integer from this array, we can use reinterpret:

julia> reinterpret(Int64, mem[1:8])
1-element reinterpret(Int64, ::Array{UInt8,1}):
 3

Note that reinterpret comes back with an array, so we can just take the first element from the result:

julia> reinterpret(Int64, mem[1:8])[1]
3

Similarly, the second element comes from mem[9:16], third element from mem[17:24] etc.

If we write a for-loop to parse the data, we have the followings:

julia> for i in 1:8
           p = (i - 1) * 8 + 1
           q = p + 8 - 1
           println(reinterpret(Int64, mem[p:q])[1])
       end
3
49
85
45
97
36
80
82

The pointer arithmetic seems awkward.... would it be easier with 0-based indexing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment