From: clement Date: Thu, 24 Oct 2019 14:22:55 +0000 (+0200) Subject: If bytes.length is odd, the last 8 bits must be ignored (same as node.js) X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=bacca5fa437a7a404ed773030190b86f874e9862;p=buffer.git If bytes.length is odd, the last 8 bits must be ignored (same as node.js) --- diff --git a/index.js b/index.js index 19b0468..49c1845 100644 --- a/index.js +++ b/index.js @@ -1076,7 +1076,8 @@ function hexSlice (buf, start, end) { function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' - for (var i = 0; i < bytes.length; i += 2) { + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res diff --git a/test/to-string.js b/test/to-string.js index 393627f..6b46875 100644 --- a/test/to-string.js +++ b/test/to-string.js @@ -33,6 +33,14 @@ test('utf16le to utf16', function (t) { t.end() }) +test('utf16le to utf16 with odd byte length input', function (t) { + t.equal( + new B(new B('abcde', 'utf8').toString('utf16le'), 'utf16le').toString('utf8'), + 'abcd' + ) + t.end() +}) + test('utf16le to hex', function (t) { t.equal( new B('abcd', 'utf16le').toString('hex'),