Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class EightyBit private (number : Int, list:List[Int]) {
- private val binaryNumArr = number.toBinaryString.split("").toList.map(_.toInt)
- println(binaryNumArr)
- private val sign = if (-1*number <= 0) 0 else 1
- var digits: List[Int] = if (list == Nil) List.fill(80-binaryNumArr.length)(0) ::: binaryNumArr else list
- private def this(digits:List[Int]) = {
- this(0, digits)
- }
- def this(num:Int) = {
- this(num, Nil)
- }
- private val sum : (List[Int], List[Int], List[Int], Int) => List[Int] = {
- case (Nil, Nil, res, 0) => res
- case (Nil, Nil, res, r) => r%2::res
- case (x::a, Nil, res, r) => res
- case (Nil, x::b, res, r) => res
- case (x1::a, x2::b, res, r) => sum(a, b, (x1+x2+r)%2::res, (x1+x2+r)/2)
- }
- def << (n: Int): EightyBit = {
- val (x,y) = this.digits.splitAt(n)
- new EightyBit(y:::List.fill(n)(0))
- }
- def + (num:EightyBit): EightyBit = {
- new EightyBit(this.sum(this.digits.reverse, num.digits.reverse, List[Int](), 0))
- }
- def * (num:EightyBit): EightyBit = {
- this.digits.reverse.zipWithIndex.foldLeft(new EightyBit(0)) { (product:EightyBit, rank:(Int, Int)) =>
- if (rank._1 == 1) product + (num << rank._2) else product
- }
- }
- def unary_- ():EightyBit = {
- val temp = new EightyBit(this.digits.map(e => if (e == 0) 1 else 0))
- val res = temp + new EightyBit(1)
- res
- }
- def value:Int = {
- this.digits.reverse.zipWithIndex.foldLeft(0) {(res:Int, rank:(Int, Int)) => res + (rank._1 * (1 << rank._2))}
- }
- }
- object Main{
- def main(args: Array[String]): Unit = {
- val a = new EightyBit(-7)
- val f = new EightyBit(5)
- 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)
- println(f.value)
- val b = new EightyBit(8)
- val c = a*b
- var d = a+b
- println(d.digits)
- d = -d
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement