Go语言:整形数字字符串转换为IPv6地址字符串

IPv6对应的整形数字为16个字节,只能用big.Int来存储。而类似于“53174336847441874194254142093255507967”这种长度的数字可以由字符串来表示,如下代码用于将数字字符串转换为对应的IPv6地址字符串。

相关文章:《Go语言:IPv6解析转换成BigInt整形以及与IPv4的兼容》

package main

import (
	"encoding/hex"
	"errors"
	"fmt"
	"math/big"
	"strings"
)

//NumToIPv6 converts a big integer represented by a string into an IPv6 address string
func NumToIPv6(numasstr string) (string, error) {
	bi, ok := new(big.Int).SetString(numasstr, 10)
	if !ok {
		return "", errors.New("fail to convert string to big.Int")
	}

	b255 := new(big.Int).SetBytes([]byte{255})
	var buf = make([]byte, 2)
	p := make([]string, 8)
	j := 0
	var i uint
	tmpint := new(big.Int)
	for i = 0; i < 16; i += 2 {
		tmpint.Rsh(bi, 120-i*8).And(tmpint, b255)
		bytes := tmpint.Bytes()
		if len(bytes) > 0 {
			buf[0] = bytes[0]
		} else {
			buf[0] = 0
		}
		tmpint.Rsh(bi, 120-(i+1)*8).And(tmpint, b255)
		bytes = tmpint.Bytes()
		if len(bytes) > 0 {
			buf[1] = bytes[0]
		} else {
			buf[1] = 0
		}
		p[j] = hex.EncodeToString(buf)
		j++
	}

	return strings.Join(p, ":"), nil
}

func convertAndPrint(numasstr string) {
	ipstr, _ := NumToIPv6(numasstr)
	fmt.Printf("%s %v\n", ipstr, numasstr)
}

func main() {
	convertAndPrint("53174336847441874194254142093255507967")
	convertAndPrint("53174336768213711679990085974688268287")
	convertAndPrint("0")
	convertAndPrint("53174312128255169743780812907543003136")
	convertAndPrint("65535")
	convertAndPrint("167904045")
	convertAndPrint("4294967295")
	convertAndPrint("281470681743360")
	convertAndPrint("281474976710655")
	convertAndPrint("281470849647405")
}

输出:

2801:0137:ffff:ffff:ffff:ffff:ffff:ffff 53174336847441874194254142093255507967
2801:0137:0000:0000:0000:ffff:ffff:ffff 53174336768213711679990085974688268287
0000:0000:0000:0000:0000:0000:0000:0000 0
2801:0000:0000:0000:0000:0000:0000:0000 53174312128255169743780812907543003136
0000:0000:0000:0000:0000:0000:0000:ffff 65535
0000:0000:0000:0000:0000:0000:0a02:032d 167904045
0000:0000:0000:0000:0000:0000:ffff:ffff 4294967295
0000:0000:0000:0000:0000:ffff:0000:0000 281470681743360
0000:0000:0000:0000:0000:ffff:ffff:ffff 281474976710655
0000:0000:0000:0000:0000:ffff:0a02:032d 281470849647405

 

你可能感兴趣的:(go,ipv6,go,ipv6,转换)