使用自定義對映 JavaScript 將十進位制的整數對映到十六進位制


通常,當我們將十進位制轉換為十六進位制(基數 16)時,我們使用集合 0123456789ABCDEF 來對映該數字。

我們需要編寫一個函式來執行完全相同的功能,但允許使用者使用除上述集合以外的任意範圍。

例如 −

The hexadecimal notation of the decimal 363 is 16B
But if the user decides to use, say, a scale ‘qwertyuiopasdfgh’ instead of
‘0123456789ABCDEF’, the number 363, then will be represented by wus

這就是我們需要做的。

因此,我們透過建立一個函式 toHex() 來完成此操作,該函式利用遞迴從整數構建一個十六進位制。準確地說,它將採用四個引數,但在這些引數中,只有前兩個引數對終端使用者有用。

第一個引數將是轉換為十六進位制的數字,第二個引數是自定義範圍,它將是可選的,如果提供,則應恰好是 16 個字元的字串,否則函式將返回 false。其他兩個引數是 hexString 和 isNegative,它們在預設情況下分別設定為一個空字串和一個布林值。

示例

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'){
      //recursively append the remainder to hex and divide num by 16
      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'))

輸出

控制檯中的輸出將為 −

WUS
16B
A05

更新於:2020 年 8 月 20 日

344 次瀏覽

啟動您的 職業生涯

完成本課程後即可獲得認證

開始
廣告