[英]Convert the big integer/decimal to a valid IPv6 address in javascript
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
如果你真的不能使用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)); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.