From f238c97c6f02cfcd294a696f5fa26b230a129561 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Wed, 11 Oct 2017 13:58:40 +0200 Subject: [PATCH] Fix asciiToHex for characters < 0x10 (#6702) --- js/src/api/util/format.js | 11 +++++++---- js/src/api/util/format.spec.js | 8 ++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/js/src/api/util/format.js b/js/src/api/util/format.js index 6a4a81d40..e981fb06d 100644 --- a/js/src/api/util/format.js +++ b/js/src/api/util/format.js @@ -75,10 +75,13 @@ export function bytesToAscii (bytes) { } export function asciiToHex (string) { - return '0x' + string.split('') - .map(s => s.charCodeAt(0)) - .map(s => s < 0x10 ? '0' + s.toString(16) : s.toString(16)) - .join(''); + let result = '0x'; + + for (let i = 0; i < string.length; ++i) { + result += ('0' + string.charCodeAt(i).toString(16)).substr(-2); + } + + return result; } export function padRight (input, length) { diff --git a/js/src/api/util/format.spec.js b/js/src/api/util/format.spec.js index ba7a3994e..4058f5364 100644 --- a/js/src/api/util/format.spec.js +++ b/js/src/api/util/format.spec.js @@ -69,6 +69,14 @@ describe('api/util/format', () => { expect(asciiToHex('abc')).to.equal('0x616263'); expect(asciiToHex('a\nb')).to.equal('0x610a62'); }); + + it('correctly converts where charCode < 0x10', () => { + expect( + asciiToHex( + [32, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0].map((v) => String.fromCharCode(v)).join('') + ) + ).to.equal('0x20100f0e0d0c0b0a09080706050403020100'); + }); }); describe('hexToAscii', () => {