eminfedar
eminfedar

Reputation: 668

Julia - read UInt32 from UInt8 Array

I have UInt8 data array which I got from TCPSocket.

I want to read UInt32s and UInt16s from different indices.

For example:

data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

// Something like this:
extracted_UInt32 = data.readUInt32(1) # [1-4]
extracted_UInt16 = data.readUInt16(5) # [5-6]

It is exactly like Node.js's Buffer.readUInt16LE(offset): https://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset

Thanks!

Upvotes: 3

Views: 945

Answers (2)

eminfedar
eminfedar

Reputation: 668

Also I have found reinterpret can be used:

data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

a = reinterpret(UInt32, data[1:4])
b = reinterpret(UInt16, data[5:6])

Upvotes: 5

fredrikekre
fredrikekre

Reputation: 10984

You can read the data as a given type from the buffer:

julia> data = IOBuffer(UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]);

julia> a = read(data, UInt32)
0x000000ff

julia> b = read(data, UInt16)
0x00aa

You can probably do this from the TCP socket directly without materializing as a vector of bytes.

Upvotes: 6

Related Questions