lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,
I'm trying to parse 12 bit numbers out of a binary file. From https://www.physionet.org/physiotools/wag/signal-5.htm:

Format 212

Each sample is represented by a 12-bit two’s complement amplitude. The first sample is obtained from the 12 least significant bits of the first byte pair (stored least significant byte first). The second sample is formed from the 4 remaining bits of the first byte pair (which are the 4 high bits of the 12-bit sample) and the next byte (which contains the remaining 8 bits of the second sample). The process is repeated for each successive pair of samples. Most of the signal files in PhysioBank are written in format 212

The file I am trying to read is here:

https://physionet.org/pn3/twadb/twa00.dat

When I use the existing tool to read the data out I get the following:

  0    -298     127
  1    -295     132
  2    -292     137
  3    -293     141
  4    -295     145
  5    -295     149
  6    -293     153
  7    -290     160
  8    -286     167
  9    -283     176

My code is here:

local filename = '/home/russellh/physionet/twadb_mod/twa00.dat'
local f = assert(io.open(filename), 'Failed to open file')
local str = f:read('*all')
f:close()

sz = 30
local index = 1
local c1,c2, samp1, samp2
local count = 0
while index < sz do
     c1, c2, index = string.unpack('<h<b', str, index)
    samp1 = c1 >> 0x04
    samp2 = c1 >> 0x0c & c2
    print(count, samp1, samp2)
    count = count + 1
end

russellh@canary-dev:~/physionet/get_stats$ lua parse-nums.lua
0 1152921504606846957 127
1 1152921504606846352 4503599627370492
2 8 0
3 1152921504606845087 0
4 1152921504606846957 4503599627370381
5 1152921504606846352 4503599627370492
6 9 0
7 1152921504606845279 0
8 1152921504606846957 4503599627370393
9 1152921504606846432 4503599627370492

My (likely erroneous) assumption is I need to convert the numbers to signed 12 bit numbers? I've tried derivations of `local t1 = (samp1 - (samp1*2)) + 4096`, all with no luck.

Thoughts?

Russ