Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 970
eminfedar Avatar asked Jul 26 '26 20:07

eminfedar


2 Answers

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.

like image 100
fredrikekre Avatar answered Jul 28 '26 09:07

fredrikekre


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])
like image 20
eminfedar Avatar answered Jul 28 '26 10:07

eminfedar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!