簡體   English   中英

在沒有Javascript內置函數的情況下將十進制轉換為十六進制

[英]Convert decimal to hexadecimal without Javascript builtin functions

嘗試將基數10轉換為基數16:

            var hex = []; //array for hexadecimals

            while (num > 0) { //if num greater than 0 loop will run

                hex=(num%16); //divides num by 16

                if (hex>9) {
                    if (hex==10) {
                        hex.unshift("A")
                    }
                    if (hex==11) {
                        hex.unshift("B")
                    }
                    if (hex==12) {
                        hex.unshift("C")
                    }
                    if (hex==13) {
                        hex.unshift("D")
                    }
                    if (hex==14) {
                        hex.unshift("E")
                    }
                    if (hex==15) {
                        hex.unshift("F")
                    }
                }

                if (hex<=9) {
                    hex.unshift(hex)
                }


            }

            alert("That decimal in hexadecimal is " + hex.join(''));
        }
    }

無論出於何種原因,這段代碼對我都不起作用...有什么想法嗎? 我正在嘗試將10,11,12,..替換為A,B,C,...,但是似乎無法正常工作。 我嘗試使用if else語句,但是在運行代碼時會崩潰。

在您的原始代碼中,您沒有更新num而您似乎誤解了%工作原理, %是模數而不是除法。

如果您不確定在鹼基之間進行轉換的方式,則可以查看此方法 ,也可以僅通過Google進行查看,那里有很多關於該算法的視頻和網站。

JavaScript的

var number = 123456; //The input value
var hexCharacters = ["A", "B", "C", "D", "E", "F"]; //Digits for 10-15, eliminates having case statements
var hexString = "";

while (number > 0) {
  var mod = number % 16; //Get the remainder
  number = Math.floor(number / 16); //Update number

  //Prepend the corresponding digit
  if (mod > 9) {
    hexString = hexCharacters[mod - 10] + hexString; //Get the digits for 10-15 from the array
  } else {
    hexString = mod.toString() + hexString;
  }
}

小提琴

快速解決方案

在您的while循環中將此行添加在hex=(num%16)行之后的某處

num = Math.floor(num / 16);

說明

您的邏輯是正確的,您只是忘記了(或不知道%沒有)將num除以16。

查看以下行(代碼中的第5行):

hex = (num % 16);     //divides num by 16

當num除以16時,它將得到余數,並將其存儲為十六進制。 到目前為止,這是正確的,因為您需要知道該值是多少。

但是,在您的注釋中,您注意到該行"divides num by 16" 不是真的。 它僅得到剩余是什么, 如果是16分,你還有做分割自己。

這行可以完成:

num = Math.floor(num / 16);

在您的while循環中。 當然,您仍然需要行hex=(num%16); 我建議您在第一行hex=(num%16);之后添加新行hex=(num%16); ,因此其目的很明確。

您編輯的代碼可能像這樣循環:

var hex = [];    // array for hexadecimals

while (num > 0) {    // if num greater than 0 loop will run

    hex = (num % 16);          // Gets remainder when num is divided by 16
    num = Math.floor(num / 16) // Actually divides num by 16

    if (hex > 9) {
        .
        .
        .

但我還是建議amura.cxg的答案,因為amura.cxg顯示了一種非常不錯的方式來重新格式化代碼,從而使代碼編寫得井井有條,簡潔明了。

我只發布我的答案,以便我可以在錯誤時准確地向您顯示代碼的位置,因為我認為這些信息對您非常有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM