PMunch / binaryparse

Binary parser for Nim
MIT License
71 stars 6 forks source link

Difference with stream read #4

Closed f-carraro closed 5 years ago

f-carraro commented 5 years ago

I'm comparing the use of binaryparse and using streams directly. Why does the following code does not result in the same output?

import streams, binaryparse

var strm = newFileStream("demodado.tem",fmRead)
strm.setPosition(0)

var datehour : array[7,uint16]

for i in 0..6:
 datehour[i] = strm.readUint16()

echo datehour

strm.setPosition(0)
createParser(simple):
  u16:field1[7]

echo simple.get(strm)
strm.close()

The echo results are:

[20, 2, 1990, 21, 44, 52, 22]
(field1: @[5120, 512, 50695, 5376, 11264, 13312, 5632])
PMunch commented 5 years ago

Because binaryparse reads in big-endian/network order. If you try to write a file from binaryparse and read the result with that then you will see that the stream reading will return the values you see from binaryparse now. Alternatively you can use the endians module to swap the endianess of the values:

import streams, binaryparse

var strm = newFileStream("demodado.tem",fmRead)
strm.setPosition(0)

var datehour : array[7,uint16]

for i in 0..6:
  datehour[i] = strm.readUint16()

echo datehour

strm.setPosition(0)
createParser(simple):
  u16:field1[7]

import sequtils, endians

var data = simple.get(strm).field1
data.apply(proc (x: var uint16) = swapEndian16(x.addr, x.addr))
echo data
strm.close()