简体   繁体   中英

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); 

Hi I am trying to convert the big integer or decimal number to valid IPv6 address I have tried the below function for it.

But this is giving all zero sets

covertToIPv6(63802943797675961899382738893456539648);

Ans: 0:0:0:0:0:0:0:0

If you really can't use BigInt or use a string representation, here's a working function that reconverts your big integer into an IPv6 address. The integer, however, must be in a string representation for this to work.

 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)); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM