Classic Mac OS Software (Discussions on Applications) > Application Development & Programming in the Classic Mac OS

string->number without multiplication

**OS923**:

What's the fastest algorithm to convert a decimal number into a binary number?

Normally I use something like

--- Code: ---n*=10;n+=s[i]-48;

--- End code ---

It should be possible with comparisons and additions. But in which order?

For example.

--- Code: ---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

--- End code ---

**IIO**:

--- Quote from: OS923 on June 08, 2018, 07:00:54 AM ---What's the fastest algorithm to convert a decimal number into a binary number?

Normally I use something like

--- Code: ---n*=10;n+=s[i]-48;

--- End code ---

It should be possible with comparisons and additions. But in which order?

--- End quote ---

the most generalized method i can think of is a series:

assuming input is a LONG with no sign, i.e. 0-2147483647)

for the LSB: input %2

for all following bits: (input / 2 - (previously calulated bit*) / 2 )

*) or actually not bit, but digit or number, because this also works for tertiary, quartiery conversion and so on.

but depending on your language you might be able to avoid arithmetics and use some form of bitwise operation. for examplee if you only need to print the bits, you can just read the bits out of the "decimal number", which, as you know, doesnt exist anyway in that form. ;)

**Naiw**:

Actually are we talking binary numbers or BCD?....

**IIO**:

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. :)

**OS923**:

When I say binary number then I mean something of the type SInt8, SInt16, SInt32, SInt64, UInt8, UInt16, UInt32, or UInt64.

So I search the fastest solution for:

--- Code: ---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);

--- End code ---

Navigation

[0] Message Index

[#] Next page

Go to full version