Skip to content

Commit

Permalink
Make bin2hex support multi-byte characters
Browse files Browse the repository at this point in the history
Fixes #427
  • Loading branch information
kvz committed Apr 5, 2024
1 parent 81dc23b commit d55a900
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/php/strings/bin2hex.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,14 @@ module.exports = function bin2hex(s) {
// returns 1: '4b6576'
// example 2: bin2hex(String.fromCharCode(0x00))
// returns 2: '00'
// example 3: bin2hex("æ")
// returns 3: 'c3a6'

let i
let l
let o = ''
let n

s += ''

for (i = 0, l = s.length; i < l; i++) {
n = s.charCodeAt(i).toString(16)
o += n.length < 2 ? '0' + n : n
const encoder = new TextEncoder()
const bytes = encoder.encode(s)
let hex = ''
for (const byte of bytes) {
hex += byte.toString(16).padStart(2, '0')
}

return o
return hex
}
6 changes: 6 additions & 0 deletions test/languages/php/strings/test-bin2hex.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,10 @@ describe('src/php/strings/bin2hex.js (tested in test/languages/php/strings/test-
expect(result).to.deep.equal(expected)
done()
})
it('should pass example 3', function (done) {
var expected = 'c3a6'
var result = bin2hex("æ")
expect(result).to.deep.equal(expected)
done()
})
})

0 comments on commit d55a900

Please sign in to comment.