Convert binary number (fixed point) to string of decimal digits

Started by
3 comments, last by kloffy 11 years, 3 months ago
I am hacking together a quick implementation of a rudimentary big number library. I am aware that there are plenty of those around, but mine is for a very specific purpose (I want it to work under the restrictions of C++ AMP). Besides, I figured that it would be a good exercise.

So, all of my arithmetic operations work (using basic textbook long multiplication and division). However, I am starting to get tired of thinking in binary. I would like to output my numbers in decimal digits. For integers, I have just implemented the naive approach.

str = "";
num = x;
do {
    digit = num%base;
    num = num/base;
    str = to_char(digit) + str;
} while (num>0);

Edit: Uhm, not sure where the rest of this went. Basically, my question was how to do the same for fixed point decimal numbers. I described an overly complicated solution and Álvaro whipped up the right answer straight away.
Advertisement

This isn't too hard. Print the integer part first, then a point, then take the fractional part, multiply it by 10 and print the integer part. Rinse, repeat.

Is that what you needed?

Oh, wow, thanks! Sometimes the simplest solutions just don't occur to me. I guess I didn't consider splitting up the integer and fractional parts.
I've written a bunch of very small bigint libraries, one of which is used in commercial products. Feel free to look over them to get some ideas.
http://homepages.ihug.co.nz/~aurora76/Malc/Useful_Classes.htm

I assume that if you plan on using AMP then performance is important?
Conversion to string in particular can be optimised by performing the divisions with the highest power of base (e.g. 10) that fits into an int (e.g. 1 billion), and then extracting the digits out of that int much quicker than if you had performed repeated divisions of the bigint by base.

You may also find this very useful: http://www.hackersdelight.org/hdcode.htm
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Very nice and comprehensive implementation, iMalc! I can definitely learn from your code, especially things like the conversions from and to float etc...

Yes performance is important, so I try not to be wasteful. However, my library prioritizes readability over high optimization. Basically, this is just a toy project to play around with AMP and see what I can do with it. The string conversion is certainly not performance critical, since it is mainly for debugging purposes.

This topic is closed to new replies.

Advertisement