go語言IP轉換uint32,uint32轉換IP
阿新 • • 發佈:2019-01-23
uint32型別轉換為IP
func UInt32ToIP(intIP uint32) net.IP { var bytes [4]byte bytes[0] = byte(intIP & 0xFF) bytes[1] = byte((intIP >> 8) & 0xFF) bytes[2] = byte((intIP >> 16) & 0xFF) bytes[3] = byte((intIP >> 24) & 0xFF) return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0]) }
IP轉換為uint32型別
func IPToUInt32(ipnr net.IP) uint32 { bits := strings.Split(ipnr.String(), ".") b0, _ := strconv.Atoi(bits[0]) b1, _ := strconv.Atoi(bits[1]) b2, _ := strconv.Atoi(bits[2]) b3, _ := strconv.Atoi(bits[3]) var sum uint32 sum += uint32(b0) << 24 sum += uint32(b1) << 16 sum += uint32(b2) << 8 sum += uint32(b3) return sum }
示例程式碼:
func main() {
// IP地址轉換為uint32
IP1 := net.ParseIP("192.168.8.44")
IPUint32 := IPToUInt32(IP1)
fmt.Println(IPUint32)
// uint32轉換為IP地址
IP2 := UInt32ToIP(IPUint32)
fmt.Println(IP2.String())
}
執行結果如下
3232237612
192.168.8.44