My question is simple: I can do 2 * 10
with shift and addition by (2 << 2) + 2
but I have no idea how to get 2.2 * 10
with shift and addition. Any suggestions will be very appreciated.
-khan_gl
My question is simple: I can do 2 * 10
with shift and addition by (2 << 2) + 2
but I have no idea how to get 2.2 * 10
with shift and addition. Any suggestions will be very appreciated.
-khan_gl
This works:
2.2 + 2.2 + 2.2 + 2.2 + 2.2 + 2.2 + 2.2 + 2.2 + 2.2 + 2.2 + (0 << 1)
Kidding aside, you can't as you can't shift floats in C++/C. Well, you can (via nasty type-punning), but then you're getting into undefined behavior.
Also, there's no point in doing it. If you're doing multiplication then just use *
. The compiler will transform it into the most efficient form.
If I understood your question at all,
2.2 = 2 + 2/10
Therefore, 2.2 * 10 = 2*10 + 2*10/10 = 2*10 + 2 = 22.
You can do division with shifts and subtractions.
On a modern CPU, floating point numbers are represented in a format called "IEEE 754".
At the core of IEEE 754 floating point arithmetic are bit shifts and integer arithmetics. If you're patient you can write a naive implementation of IEEE 754 ALU in C. You might find this thread interesting: