From bacca5fa437a7a404ed773030190b86f874e9862 Mon Sep 17 00:00:00 2001 From: clement Date: Thu, 24 Oct 2019 16:22:55 +0200 Subject: [PATCH] If bytes.length is odd, the last 8 bits must be ignored (same as node.js) --- index.js | 3 ++- test/to-string.js | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) 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'), -- 2.34.1