Chuyển thập phân sang hex (cơ số 16) thường dùng '0123456789ABCDEF'. Cho phép dùng bảng ký tự tùy chỉnh 16 ký tự.
Ví dụ: 363 → '16B' (hex chuẩn). Với bảng 'qwertyuiopasdfgh' → 'wus'.
Hàm toHex() đệ quy, 4 tham số (2 đầu quan trọng): số, bảng tùy chọn (optional, phải 16 ký tự).
Ví dụ
const num = 363; const toHex = ( num, hexString = '0123456789ABCDEF', hex = '', isNegative = num < 0 ) => { if(hexString.length !== 16){ return false; } num = Math.abs(num); if(num && typeof num === 'number'){ return toHex(Math.floor(num / 16), hexString, `${hexString[num%16]}${hex}`, isNegative); }; return isNegative ? `-${hex}` : hex; }; console.log(toHex(num, 'QWERTYUIOPASDFGH')); console.log(toHex(num)); console.log(toHex(num, 'QAZWSX0123456789'))Kết quả
Đầu ra console:
WUS 16B A05