How to convert an arbitrary large integer from base 10 to base 16?

后端 未结 7 1916
旧时难觅i
旧时难觅i 2021-02-04 21:39

The program requires an input of an arbitrary large unsigned integer which is expressed as one string in base 10. The outputs is another string that expresses the integer in bas

7条回答
  •  走了就别回头了
    2021-02-04 22:13

    Here is the above-mentioned algorithm implemented in javascript:

    function addDecValue(hexArray, value) {
      let carryover = value;
      for (let i = (hexArray.length - 1); i >= 0; i--) {
        let rawDigit = ((hexArray[i] || 0) * 10) + carryover;
        hexArray[i] = rawDigit % 16;
        carryover = Math.floor(rawDigit / 16);
      }
    }
    
    function toHexArray(decimalString) {
      let hexArray = new Array(decimalString.length);
      for (let i = 0; i < decimalString.length; i++) {
        addDecValue(hexArray, Number(decimalString.charAt(i)));
      }
      return hexArray;
    }
    
    function toHexString(hexArray) {
      const hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
      let result = '';
      for (let i = 0; i < hexArray.length; i++) {
        if (result === '' && hexArray[i] === 0) continue;
        result += hexDigits[hexArray[i]];
      }
      return result
    }
    
    toHexString(toHexArray('1234567890987654321234567890987654321234567890987654321'));
    

提交回复
热议问题