n*=10;n+=s[i]-48;
s="\p123456789"
t=reverse(s)
switch (t[1])
case "9": d+=9
and so on
switch (t[2])
case "9": d+=90
and so on
What's the fastest algorithm to convert a decimal number into a binary number?
Normally I use something likeCode: [Select]n*=10;n+=s[i]-48;
It should be possible with comparisons and additions. But in which order?
bool Convert(ConstStringPtr s,SInt8 &n);
bool Convert(ConstStringPtr s,SInt16 &n);
bool Convert(ConstStringPtr s,SInt32 &n);
bool Convert(ConstStringPtr s,SInt64 &n);
bool Convert(ConstStringPtr s,UInt8 &n);
bool Convert(ConstStringPtr s,UInt16 &n);
bool Convert(ConstStringPtr s,UInt32 &n);
bool Convert(ConstStringPtr s,UInt64 &n);
in the other thread he was talking about a "string", but i think the arithmetics (or other possible ways hot to solve the problem) wont differ much f rom a case where an array of 0 and 1 is the desried inout/output. :)
while the data type (or even its length) might not matter, the type of conversion can differ a lot for CPU.
i dont know his programmming langauge at all, but i bet that sprintf consumes far more than arithmetics or epxr based, and a possible bitwise processing solution is the best.
something like printf or regexp works on a different level and has (depending on the enviroment) an overhard of mabye 10 or 50 times compared to multiplication/addition/modulus/...
of course, if you only need a certain type of data, it might (in some languages) be enough to change the "header" (or whatever it is. this will be needing less CPU than a radix conversion of a 32 bit int (with output format 32 bit int, or, for longer numbers, an array of SHORT or ASCI or whatever to store the 0 and 1 in.)
n=0;
while (*s)
{
n*=10;
n+=static_cast<char>(*s-48);
s++;
}
This starts with multiplying zero by 10, which is lost time. if (n) n*=10; is faster than n*=10; because the time that you win by eliminating one multiplication is longer than the time that you lose with several comparisons.
#define consume() n+=*s++;n-=48
n=0;
if (!*s) return;
consume();
while (*s)
{
n*=10;
consume();
}
This saves 1 multiplication with only 1 extra comparison.
#include <NumberFormatting.h>
#include <iostream>
using namespace std;
int main()
{
SInt32 x;
::StringToNum("\p00123",
&x);
cout << x << endl;
::StringToNum("\p+00123",
&x);
cout << x << endl;
::StringToNum("\p-00123",
&x);
cout << x << endl;
::StringToNum("\p 123",
&x);
cout << x << endl;
::StringToNum("\p+ 123",
&x);
cout << x << endl;
::StringToNum("\p- 123",
&x);
cout << x << endl;
::StringToNum("\p 00123",
&x);
cout << x << endl;
::StringToNum("\p+ 00123",
&x);
cout << x << endl;
::StringToNum("\p- 00123",
&x);
cout << x << endl;
::StringToNum("\p -123",
&x);
cout << x << endl; // -> 13123.
::StringToNum("\p -00123",
&x);
cout << x << endl; // -> 1300123.
return 0;
}