如何在JavaScript中将十进制转换为十六进制

2020/09/16 14:31 · javascript ·  · 0评论

``hexString = yourNumber.toString(16);``

``yourNumber = parseInt(hexString, 16);``

``````function decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}

return number.toString(16).toUpperCase();
}

console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));``````

``````function decimalToHex(d, padding) {
var hex = Number(d).toString(16);

hex = "0" + hex;
}

return hex;
}``````
``````function toHex(d) {
return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}``````

``````> (-1).toString(16)
"-1"

> ((-2)>>>0).toString(16)
"fffffffe"``````

``````function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}``````

``````function decimalToHex(d) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}

// Or "#000000".substr(0, 7 - hex.length) + hex;
// Or whatever
// *Thanks to MSDN``````

``for (var i = 0; i < hex.length; i++){}``

``for (var i = 0, var j = hex.length; i < j; i++){}``

``````function rgb2hex(r,g,b) {
if (g !== undefined)
return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
else
return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}``````

``````function numHex(s)
{
var a = s.toString(16);
if ((a.length % 2) > 0) {
a = "0" + a;
}
return a;
}``````

``````function strHex(s)
{
var a = "";
for (var i=0; i<s.length; i++) {
a = a + numHex(s.charCodeAt(i));
}

return a;
}``````

``````function toHex(s)
{
var re = new RegExp(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*\$/);

if (re.test(s)) {
return '#' + strHex( s.toString());
}
else {
return 'A' + strHex(s);
}
}``````

``````/////////////////////////////////////////////////////////////////////////////
//  toHex().  Convert an ASCII string to hexadecimal.
/////////////////////////////////////////////////////////////////////////////
toHex(s)
{
if (s.substr(0,2).toLowerCase() == "0x") {
return s;
}

var l = "0123456789ABCDEF";
var o = "";

if (typeof s != "string") {
s = s.toString();
}
for (var i=0; i<s.length; i++) {
var c = s.charCodeAt(i);

o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);
}

return "0x" + o;
}``````

``````/////////////////////////////////////////////////////////////////////////////
//  fromHex().  Convert a hex string to ASCII text.
/////////////////////////////////////////////////////////////////////////////
fromHex(s)
{
var start = 0;
var o = "";

if (s.substr(0,2).toLowerCase() == "0x") {
start = 2;
}

if (typeof s != "string") {
s = s.toString();
}
for (var i=start; i<s.length; i+=2) {
var c = s.substr(i, 2);

o = o + String.fromCharCode(parseInt(c, 16));
}

return o;
}``````

``````<?php

echo <<<EOD
<html>
<script>
var a = -3.14159265;
alert( "A = " + a );
var b = a.toString();
alert( "B = " + b );
</script>
<body>
</body>
</html>
EOD;

?>``````

``````function decToHex(dec) {
return (dec + Math.pow(16, 6)).toString(16).substr(-6)
}``````

``````let c = 4210330 // your color in decimal format
let rgb = [(c & 0xff0000) >> 16,  (c & 0x00ff00) >> 8,  (c & 0x0000ff)]

// Vanilla JS:
document..getElementById('some-element').style.color = 'rgb(' + rgb + ')'
// jQuery:
\$('#some-element').css('color', 'rgb(' + rgb + ')')``````

``````var number = 3200;
var hexString = number.toString(16);``````

16是基数，十六进制数中有16个值：-)

``````const convert = {
bin2dec : s => parseInt(s, 2).toString(10),
bin2hex : s => parseInt(s, 2).toString(16),
dec2bin : s => parseInt(s, 10).toString(2),
dec2hex : s => parseInt(s, 10).toString(16),
hex2bin : s => parseInt(s, 16).toString(2),
hex2dec : s => parseInt(s, 16).toString(10)
};

convert.bin2dec('111'); // '7'
convert.dec2hex('42');  // '2a'
convert.hex2bin('f8');  // '11111000'
convert.dec2bin('22');  // '10110'``````

``````function decimalToHex(decimal, chars) {
return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}``````

``````function toHexString(n) {
if(n < 0) {
n = 0xFFFFFFFF + n + 1;
}
return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}``````
``````function dec2hex(i)
{
var result = "0000";
if      (i >= 0    && i <= 15)    { result = "000" + i.toString(16); }
else if (i >= 16   && i <= 255)   { result = "00"  + i.toString(16); }
else if (i >= 256  && i <= 4095)  { result = "0"   + i.toString(16); }
else if (i >= 4096 && i <= 65535) { result =         i.toString(16); }
return result
}``````

AFAIK 评论5780​​7是错误的，应类似于：
var hex = Number（d）.toString（16）;

var hex = parseInt（d，16）;

``````function decimalToHex(d, padding) {
var hex = Number(d).toString(16);

hex = "0" + hex;
}

return hex;
}``````

``````function hexdec (hex_string) {
hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);
hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);
return parseInt(hex_string, 10);
}``````

`.toString(16)`因为我需要负值进行正确编码，所以简单对我不起作用。到目前为止，以下代码是我测试过的最快的1-2个字节的值（请注意，它`symbols`定义了要获取的输出符号的数量，对于4个字节的整数，它应等于8）：

``````var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
var result = '';
while (symbols--) {
result = hex[num & 0xF] + result;
num >>= 4;
}
return result;
}``````

``````// Avoids a hard-to-track-down bug by returning `c` instead of `12`
(+"12").toString(16);``````

``var dec = +("0x" + hex);``

``````function DecToHex(decimal) { // Data (decimal)

length = -1;    // Base string length
string = '';    // Source 'string'

characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array

do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift

string += characters[decimal & 0xF];   // Mask byte, get that character
++length;                              // Increment to length of string

} while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0

decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'

do
decimal += string[length];
while (length--); // Flip string forwards, with the prefixed '0x'

}

/* Original: */

D = 3678;    // Data (decimal)
C = 0xF;    // Check
A = D;        // Accumulate
B = -1;        // Base string length
S = '';        // Source 'string'
H = '0x';    // Destination 'string'

do {
++B;
A& = C;

switch(A) {
case 0xA: A='A'
break;

case 0xB: A='B'
break;

case 0xC: A='C'
break;

case 0xD: A='D'
break;

case 0xE: A='E'
break;

case 0xF: A='F'
break;

A = (A);
}
S += A;

D >>>= 0x04;
A = D;
} while(D)

do
H += S[B];
while (B--)

S = B = A = C = D; // Zero out variables

``````function toHex(i, pad) {

}

var strToParse = i.toString(16);

strToParse = "0" + strToParse;
}

var finalVal =  parseInt(strToParse, 16);

if ( finalVal < 0 ) {
finalVal = 0xFFFFFFFF + finalVal + 1;
}

return finalVal;
}``````

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

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

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

``````  numToHex = function(num) {
var r=((0xff0000&num)>>16).toString(16),
g=((0x00ff00&num)>>8).toString(16),
b=(0x0000ff&num).toString(16);
if (r.length==1) { r = '0'+r; }
if (g.length==1) { g = '0'+g; }
if (b.length==1) { b = '0'+b; }
return '0x'+r+g+b;                 // ('#' instead of'0x' for CSS)
};

var dec = 5974678;
console.log( numToHex(dec) );        // 0x5b2a96``````

``const toHex = num => (num).toString(16).toUpperCase();``

``````const hugeNumber = "9007199254740991873839" // Make sure its in String
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);
console.log(hexOfHugeNumber)``````

``````function decimalToPaddedHexString(number, bitsize)
{
let byteCount = Math.ceil(bitsize/8);
let maxBinValue = Math.pow(2, bitsize)-1;

/* In node.js this function fails for bitsize above 32bits */
if (bitsize > 32)
throw "number above maximum value";

/* Conversion to unsigned form based on  */
if (number < 0)
number = maxBinValue + number + 1;

}``````

``````for (let n = 0 ; n < 64 ; n++ ) {
}``````

``````decimalToPaddedHexString(-1, 0) =        0x0 =                                0b0
decimalToPaddedHexString(-1, 1) =       0x01 =                                0b1
decimalToPaddedHexString(-1, 2) =       0x03 =                               0b11
decimalToPaddedHexString(-1, 3) =       0x07 =                              0b111
decimalToPaddedHexString(-1, 4) =       0x0F =                             0b1111
decimalToPaddedHexString(-1, 5) =       0x1F =                            0b11111
decimalToPaddedHexString(-1, 6) =       0x3F =                           0b111111
decimalToPaddedHexString(-1, 7) =       0x7F =                          0b1111111
decimalToPaddedHexString(-1, 8) =       0xFF =                         0b11111111
decimalToPaddedHexString(-1, 9) =     0x01FF =                        0b111111111
Thrown: 'number above maximum value'``````

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

Math.abs（N）函数将负数转换为正数，并且作为奖励，它看起来不像有人通过削片机运行。