题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

主要是将ip分解,并对每一位进行二进制位移转换后得到10进制数据也就是我们得到的数据。

IPv4使用4节表示,其中每节可表示数字范围如下:

1、4294967296

2、16777216

3、65536

4、256
package main

import (
    "fmt"
    "strings"
    "strconv"
)

func main(){
    for {
    var a string 
    n,_:=fmt.Scan(&a)
    if n==0{
        break
    }else{
        ip := strings.Split(a,".")
        if len(ip)==4{
            ip1,_ :=strconv.Atoi(ip[0])
            ip2,_ :=strconv.Atoi(ip[1])
            ip3,_ :=strconv.Atoi(ip[2])
            ip4,_ :=strconv.Atoi(ip[3])
            b := uint(ip1)<<24 | uint(ip2)<<16 | uint(ip3)<<8 |uint(ip4)
            fmt.Println(b)
        }else{
            ip1 ,_:=  strconv.Atoi(a)
            ip2 ,_:=  strconv.Atoi(a)
            ip3 ,_:=  strconv.Atoi(a)
            ip4 ,_:=  strconv.Atoi(a)
            fmt.Println(strconv.Itoa((ip1>>24) & 255)+"."+strconv.Itoa(ip2>>16 & 255)+"."+strconv.Itoa(ip3>>8& 255)+"."+strconv.Itoa(ip4& 255))
        }
        
    }
    }
}
全部评论

相关推荐

评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务