How to convert decimal to hexadecimal in JavaScript

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

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

27条回答
  •  遥遥无期
    2020-11-21 23:47

    I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:

    ((0xFF + number +1) & 0x0FF).toString(16);
    

    You can use this instruction to any number bytes, only you add FF in respective places. For example, to two bytes:

    ((0xFFFF + number +1) & 0x0FFFF).toString(16);
    

    If you want cast an array integer to string hexadecimal:

    s = "";
    for(var i = 0; i < arrayNumber.length; ++i) {
        s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
    }
    

提交回复
热议问题