-
Notifications
You must be signed in to change notification settings - Fork 0
/
hex.js
35 lines (34 loc) · 1.27 KB
/
hex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// https://github.com/danfinlay/browser-string-hexer/blob/main/index.js
export default function hexer(input) {
const utf8 = toUTF8Array(input)
const hex = utf8.map((n) => n.toString(16))
return '0x' + hex.join('')
}
// From https://stackoverflow.com/a/18729931
function toUTF8Array(str) {
var utf8 = []
for (var i = 0; i < str.length; i++) {
var charcode = str.charCodeAt(i)
if (charcode < 0x80) utf8.push(charcode)
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f))
} else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode >> 6) & 0x3f), 0x80 | (charcode & 0x3f))
}
// surrogate pair
else {
i++
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff))
utf8.push(
0xf0 | (charcode >> 18),
0x80 | ((charcode >> 12) & 0x3f),
0x80 | ((charcode >> 6) & 0x3f),
0x80 | (charcode & 0x3f)
)
}
}
return utf8
}