function covertToIPv6(IP)
{
var ip = "";
ip = ((IP >> 112 ) & 0xFFFF) + ":" + ((IP >> 96 ) & 0xFFFF) + ":" + ((IP
>> 80 ) & 0xFFFF) + ":" +((IP >> 64 ) & 0xFFFF) + ":" + ((IP >> 48 ) &
0xFFFF) + ":" + ((IP >> 32 ) & 0xFFFF) + ":" + ((IP >> 16 ) & 0xFFFF) +
":"+( IP & 0xFFFF);
console.log(ip);
}
covertToIPv6(63802943797675961899382738893456539648);
嗨,我正在尝试将大整数或小数号转换为有效的IPv6 address
我已经尝试了以下功能。
这给出了所有零集
covertToIPv6(63802943797675961899382738893456539648);
ans:0:0:0:0:0:0:0:0:0
如果您真的无法使用BigInt
或使用字符串表示形式,则是将您的大整数重新转换为IPv6地址的工作功能。但是,整数必须在字符串表示中才能起作用。
var divide = function(dividend, divisor) {
var returnValue = "";
var remainder = 0;
var currentDividend = 0,
currentQuotient;
dividend.split("").forEach(function(digit, index) {
// use classical digit by digit division
if (currentDividend !== 0) {
currentDividend = currentDividend * 10;
}
currentDividend += parseInt(digit);
if (currentDividend >= divisor) {
currentQuotient = Math.floor(currentDividend / divisor);
currentDividend -= currentQuotient * divisor;
returnValue += currentQuotient.toString();
} else if (returnValue.length > 0) {
returnValue += "0";
}
if (index === dividend.length - 1) {
remainder = currentDividend;
}
});
return {
quotient: returnValue.length === 0 ? "0" : returnValue,
remainder: remainder
};
};
var convertToIPv6 = function(input, base) {
base = base || 10;
var blocks = [];
var blockSize = Math.pow(2, 16); // 16 bit per block
while (blocks.length < 8) {
var divisionResult = divide(input, blockSize);
// The remainder is the block value
blocks.unshift(divisionResult.remainder.toString(base));
// The quotient will be used as dividend for the next block
input = divisionResult.quotient;
}
return blocks.join(":");
};
// Examples
["63802943797675961899382738893456539648",
"16894619001915479834806084984789761616",
"734987203501750431791304671034703170303"
].forEach(function(input) {
console.log("Input:", input);
console.log("IP address (decimal):", convertToIPv6(input));
console.log("IP address (hex):", convertToIPv6(input, 16));
});