Created
August 22, 2014 04:10
-
-
Save viruschidai/dfd169c799963605dc87 to your computer and use it in GitHub Desktop.
pack puzzle
This file contains 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
exports.pack = (data, cb) -> | |
ret= [] | |
innerRet = [] | |
for index, d of data | |
if d then innerRet.push '1' else innerRet.push '0' | |
if innerRet.length is 32 or index is (data.length - 1) | |
ret.push innerRet | |
innerRet = [] | |
binary = [] | |
for part in ret | |
binaryStr = part.join('') | |
binary.push parseInt binaryStr, 2 | |
binary.push data.length | |
cb null, binary | |
exports.unpack = (buffer, cb) -> | |
ret = '' | |
arrayLength = buffer[buffer.length-1] | |
for v in buffer[0..buffer.length-1] | |
binaryStr = v.toString(2) | |
if binaryStr.length < 32 | |
padding = '00000000000000000000000000000000'.substring 0, 32 - binaryStr.length | |
binaryStr = padding + binaryStr | |
ret += binaryStr | |
ret = ret.substring 0, arrayLength | |
data = [] | |
for v in ret | |
if v is '1' then data.push true else data.push false | |
cb null, data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment