titan
titan

Reputation: 122

converting decimal fraction to binary fraction in Scala

I have a sequence of decimal numbers between 1 and 2. After taking their reciprocal, I want the number converted in binary form so that I can isolate the 10 MSBs of the reciprocal. I don't want to convert it in IEEE-754 floating point representation, but simply in binary format.

reciprocal = 1.0/3.0
Double = 0.3333333333333333 

The above number on manually converting to binary will give me an infinite bit stream:

reciprocalBits = 0.0101010101010101010101010101010101010101010101010101...

I want the 10 most-significant bits of the above binary number. How do I convert reciprocal to reciprocalBits in Scala.

Upvotes: 1

Views: 540

Answers (1)

jwvh
jwvh

Reputation: 51271

scala> val reciprocal = 1.0/3.0
reciprocal: Double = 0.3333333333333333

scala> List.tabulate(10)(x => ((reciprocal * math.pow(2,x)).toInt % 2))
res0: List[Int] = List(0, 0, 1, 0, 1, 0, 1, 0, 1, 0)

Upvotes: 1

Related Questions