Scala之IP 和 Number转换

上代码

package club.xyes.spark.day2

import java.util.regex.Pattern

import scala.collection.mutable.ArrayBuffer

object Utils {
  val ip_reg = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)")

  implicit def string2Int(str: String): Int = {
    Integer.parseInt(str)
    //str.toInt 不能用 不知道啥意思 有人知道欢迎指点
  }

  def ip2Number(ip: String): Long = {
    val mt = ip_reg.matcher(ip)
    if (mt.find()) {
      var re: Long = 0
      for (i <- 1 to 4) {
        re += mt.group(i)
        if (i != 4) re <<= 8
      }
      re
    } else {
      0
    }
  }

  def number2Ip(number: Long): String = {
    var n = number
    val arr = ArrayBuffer[Long]()
    for (i <- 1 to 4) {
      val ni = n & 0xFF
      arr += ni
      n >>= 8
    }
    val sb = new StringBuilder
    for (s <- arr.reverse) {
      sb.append(s).append(".")
    }
    sb.deleteCharAt(sb.length - 1)
    sb.toString
  }
}

你可能感兴趣的:(算法,scala)