Advertisement
Guest User

Untitled

a guest
Mar 21st, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.00 KB | None | 0 0
  1.  
  2. class EightyBit private (number : Int, list:List[Int]) {
  3.   private val binaryNumArr = number.toBinaryString.split("").toList.map(_.toInt)
  4.   println(binaryNumArr)
  5.   private val sign = if (-1*number <= 0) 0 else 1
  6.   var digits: List[Int] = if (list == Nil) List.fill(80-binaryNumArr.length)(0) ::: binaryNumArr  else list
  7.  
  8.   private def this(digits:List[Int]) = {
  9.     this(0, digits)
  10.   }
  11.  
  12.   def this(num:Int) = {
  13.     this(num, Nil)
  14.   }
  15.  
  16.   private val sum : (List[Int], List[Int], List[Int], Int) => List[Int] = {
  17.     case (Nil, Nil, res, 0) => res
  18.     case (Nil, Nil, res, r) => r%2::res
  19.     case (x::a, Nil, res, r) => res
  20.     case (Nil, x::b, res, r) => res
  21.     case (x1::a, x2::b, res, r) => sum(a, b, (x1+x2+r)%2::res, (x1+x2+r)/2)
  22.   }
  23.  
  24.   def << (n: Int): EightyBit = {
  25.     val (x,y) = this.digits.splitAt(n)
  26.     new EightyBit(y:::List.fill(n)(0))
  27.   }
  28.  
  29.   def + (num:EightyBit): EightyBit = {
  30.     new EightyBit(this.sum(this.digits.reverse, num.digits.reverse, List[Int](), 0))
  31.   }
  32.  
  33.   def * (num:EightyBit): EightyBit = {
  34.     this.digits.reverse.zipWithIndex.foldLeft(new EightyBit(0)) { (product:EightyBit, rank:(Int, Int)) =>
  35.       if (rank._1 == 1) product + (num << rank._2) else product
  36.     }
  37.   }
  38.  
  39.   def unary_- ():EightyBit = {
  40.     val temp = new EightyBit(this.digits.map(e => if (e == 0) 1 else 0))
  41.     val res = temp + new EightyBit(1)
  42.     res
  43.   }
  44.  
  45.   def value:Int = {
  46.     this.digits.reverse.zipWithIndex.foldLeft(0) {(res:Int, rank:(Int, Int)) => res + (rank._1 * (1 << rank._2))}
  47.   }
  48.  
  49. }
  50.  
  51. object Main{
  52.   def main(args: Array[String]): Unit = {
  53.     val a = new EightyBit(-7)
  54.     val f = new EightyBit(5)
  55.     f.digits = List(1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)
  56.     println(f.value)
  57.     val b = new EightyBit(8)
  58.     val c = a*b
  59.     var d = a+b
  60.     println(d.digits)
  61.     d = -d
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement