rendezvous/www/lib/hex2bin.js

54 lines
976 B
JavaScript
Raw Normal View History

2023-06-21 15:33:47 +00:00
//
// 2022.08.09
//
// ------------------------------
export default function bin2hex(n){
n = n || ''
// \\
// ! \\ lossy on bad data
/////
const l = n.length
const c = l>>1
const a = new Uint8Array(c)
for(let i=0;i<c;i++){
const p = i<<1
const s = n.substring(p,p+2)
console.log({i,p,s})
a[i] = parseInt(s,16)
}
return a
}
//console.log(bin2hex('aabbcc'))
//console.log(bin2hex('000102'))
//console.log(bin2hex('FDFEFF'))
/*
https://github.com/LinusU/hex-to-array-buffer/blob/master/index.js
export default function hexToArrayBuffer (input) {
if (typeof input !== 'string') {
throw new TypeError('Expected input to be a string')
}
if ((input.length % 2) !== 0) {
throw new RangeError('Expected string to be an even number of characters')
}
const view = new Uint8Array(input.length / 2)
for (let i = 0; i < input.length; i += 2) {
view[i / 2] = parseInt(input.substring(i, i + 2), 16)
}
return view.buffer
}
*/