How to convert decimal to hexadecimal in JavaScript

后端 未结 27 3049
臣服心动
臣服心动 2020-11-21 23:05

How do you convert decimal values to their hexadecimal equivalent in JavaScript?

27条回答
  •  失恋的感觉
    2020-11-21 23:38

    Here's my solution:

    hex = function(number) {
      return '0x' + Math.abs(number).toString(16);
    }
    

    The question says: "How to convert decimal to hexadecimal in JavaScript". While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish hexadecimal codes from programmatic identifiers and other numbers (1234 could be hexadecimal, decimal, or even octal).

    Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.

    The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.

    The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.

提交回复
热议问题