码迷,mamicode.com
首页 > 其他好文 > 详细

scala ip转换器

时间:2015-12-07 02:17:41      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

spark在运算过程需要根据ip得到对应省份和城市的信息,需要把ip地址转变成数字,才能进行进行操作。下面就是用scala对ip地址和数字进行相互转换的代码。

object ip {
def main(args: Array[String]) {
long2ip(ip2long("12222.168.1.1000"))
}

def ip2long(ip: String): Long ={
val Array(a, b, c, d) = ip.split( """\.""")
val retVal = (a.toLong << 24) + (b.toLong << 16) + (c.toLong << 8) + (d.toLong)
printf(s"value=$retVal\n")
retVal
}

def long2ip(ip:Long): Unit ={

val a:Long = (ip >>> 24) & 0xff
val b:Long = (ip >>> 16) & 0xff
val c:Long = (ip >>> 8) & 0xff
val d:Long = (ip) & 0xff

printf(s"ip=$a.$b.$c.$d")
}
}

scala ip转换器

标签:

原文地址:http://www.cnblogs.com/luckuan/p/5024896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!