PDA

View Full Version : Turning Text Numbers into a 32bit number

Philldapill
01-12-2008, 01:57 AM
I'm tying to make a routine that can translate a·character·array into a real number. The array will only consist of characters 0-9, so no letters or other characters will be included. What I want to do, is make a routine that will go through the array, element by element and turn the character into a real number that I can later use in the code. Basically, if I had an array like this:
MyArray[0] := 2
MyArray[1] := 4
MyArray[2] := 1

I would want to turn it into the number 241 in a decimal. How do I do this, other than making a routine that just matches the character code up to a 1 digit number, e.g., char "1" = character 49, char "2" = character 50, etc. etc.

Mike Green
01-12-2008, 02:57 AM
The "format" object (or the "numbers" object) in the object exchange should be able to do what you want. Download it and have a look. It essentially implements the input and output string to/from number routines in C. It works for integers, but you could use the floating point package (also in the object exchange) to convert the integers to floating point. If you want to include embedded decimal points, you'll probably have to write your own routines using the floating point package or modify the routines in the "numbers" object to work with floating point rather than integer arithmetic.

Philldapill
01-12-2008, 05:41 AM
Great. Thanks mike. Here's a simple function I made that does it pretty well(I think).
PUB CharToDec(num)
if(num => 48 AND num =< 57) 'If the character input has a hex value between 48 and 57(0-9)
return (num - 48)
else
return -1

deSilva
01-12-2008, 05:55 AM
Up to this moment is was not quite clear to me what you intended to do.. But note:
You can also write
"0" rather than 48
and
"9" rather than 57

Philldapill
01-12-2008, 05:59 AM
Really? Yeah, that would be more readable... Btw, excuse the formatting. I'm sure you guys now about the forum deleting spaces when you post code...

Peter Verkaik
01-12-2008, 06:17 AM
If you use·the Format object, you can just do
OBJ
· fmt: "Format"
VAR
· long i
· long j[0]
· byte value[4]
PUB
· value[0] = "2"· 'simulate a number as string
· value[1] = "4"
· value[2] = "1"
· value[3] = 0·· 'must have a closing null
· i := fmt.atoi(@value) 'convert signed decimal string to integer value

Now i holds the value 241

You can also use
· fmt.sscanf(@value,string("%d"),@j)
· then j[0] will hold 241
but in this case atoi is simpler.

regards peter

deSilva
01-12-2008, 06:17 AM
We also know what to do against it:
surround your code with [ code ] [ /code ] and leave a space after each opening bracket within your code.

You can also use this fine link to convert your text into pretty printing
www.phipi.com/format (http://www.phipi.com/format)

Post Edited (deSilva) : 1/11/2008 11:24:05 PM GMT

Philldapill
01-12-2008, 06:49 AM
I love it. Thanks deSilva.

Again, I love it Peter!

(Oh, and thanks Phil for the formatter!)