Created
August 22, 2014 04:03
-
-
Save runk/f908c1be5928724918eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
assert = require 'assert' | |
# data = require './data.json' | |
exports.pack = (data, cb) -> | |
binary = data.map(Number).join('') | |
octets = [] | |
bytes = Math.ceil(binary.length / 8) | |
# console.log {bytes} | |
buffer = new Buffer(bytes) | |
for i in [0...bytes] | |
octet = binary.substring(i * 8, i * 8 + 8) | |
buffer.writeUInt8 parseInt(octet, 2), i | |
cb null, buffer | |
exports.unpack = (buffer, cb) -> | |
bytes = buffer.length | |
binary = '' | |
for i in [0...bytes] | |
octet = buffer.readUInt8(i).toString 2 | |
if octet.length < 8 | |
octet = Array(9 - octet.length).join('0') + octet | |
binary += octet | |
cb null, binary.split('').map(Number).map Boolean | |
# b = pack(data) | |
# console.log b | |
# a = unpack b | |
# assert.deepEqual a, data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment