Bug in Writer.prototype.writeVarInt
harlos0517 opened this issue · 0 comments
harlos0517 commented
The original code (midi-writer.js:309) parses integers in the wrong way : only the first bit of MSB is 1.
> 18432456468
10000100
01010101
00100011
01101110
00010100
The correct result is that the first bit of all bytes except LSB is 1.
> 18432456468
10000100
11010101
10100011
11101110
00010100
The fixed test code I'm using :
const leftpad = require('left-pad')
var v = 18432456468
if (v < 0) throw "Cannot write negative variable-length integer"
if (v <= 0x7F) {
console.log(leftpad(v.toString(2),8,'0'))
} else {
var i = v
var bytes = []
bytes.push(i & 0x7F)
i >>= 7
while (i) {
var b = i & 0x7F | 0x80
bytes.push(b)
i >>= 7
}
bytes.reverse().forEach((e,i)=>{
console.log(leftpad(e.toString(2),8,'0'))
})
}
midi-writer.js:309 should be
Writer.prototype.writeVarInt = function(v) {
if (v < 0) throw "Cannot write negative variable-length integer"
if (v <= 0x7F) {
this.writeUInt8(v)
} else {
var i = v
var bytes = []
bytes.push(i & 0x7F)
i >>= 7
while (i) {
var b = i & 0x7F | 0x80
bytes.push(b)
i >>= 7
}
this.writeBytes(bytes.reverse())
}
}
I was trying to use this package for handling some midi data and found this bug.
Hope you can fix it, thanks.
Deemo Harlos