Skip to content

Instantly share code, notes, and snippets.

@davidguttman
Created December 31, 2014 17:23
Show Gist options
  • Save davidguttman/89141cc17295f567a56f to your computer and use it in GitHub Desktop.
Save davidguttman/89141cc17295f567a56f to your computer and use it in GitHub Desktop.
var tape = require('tape')
var bitfield = new Buffer(require('./fixtures/location-bitfield.json'))
tape.only('should parse location bitfield', function(t) {
var parsed = parse(bitfield)
var expected = {
deltaHeading: 0,
x: 10936,
y: 7856,
animation: 0,
z: 1011,
deltaY: 0,
deltaX: 0,
heading: 1627,
deltaZ: 0 }
t.deepEqual(parsed, expected, 'should parse bitfield')
t.end()
})
function parse (buf) {
var parsed =
{ deltaHeading: extract(buf.slice(0), 0, 10)
, x: extract(buf.slice(0), 10, 19)
, y: extract(buf.slice(4), 0, 19)
, animation: extract(buf.slice(4), 19, 10)
, z: extract(buf.slice(8), 0, 19)
, deltaY: extract(buf.slice(8), 19, 13)
, deltaX: extract(buf.slice(12), 0, 13)
, heading: extract(buf.slice(12), 13, 12)
, deltaZ: extract(buf.slice(16), 0, 13)
}
return parsed
}
function extract (buf, offset, length) {
var full = buf.readInt32LE(0)
var mask = makeBitMask(length)
return (full >> offset) & mask
}
function makeBitMask (n) {
var str = ''
for (var i = 0; i < n; i++) {
str += 1
}
return parseInt(str, 2)
}
// , /*0094*/ deltaHeading: vs.Int16LE:10
// , /*----*/ x: vs.Int16LE:19
// , /*----*/ padding0054: vs.Int16LE:3
// , /*0098*/ y: vs.Int16LE:19
// , /*----*/ animation: vs.Int16LE:10
// , /*----*/ padding0058: vs.Int16LE:3
// , /*0102*/ z: vs.Int16LE:19
// , /*----*/ deltaY: vs.Int16LE:13
// , /*0106*/ deltaX: vs.Int16LE:13
// , /*----*/ heading: vs.UInt16LE:12
// , /*----*/ padding0066: vs.Int16LE:7
// , /*0110*/ deltaZ: vs.Int16LE:13
// , /*----*/ padding0070: vs.Int16LE:19
// x = (firstInt >> 10) & 524287 (524287 is 0b1111111111111111111 (19 one's))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment