Turning Text Numbers into a 32bit number
Philldapill
Posts: 1,283
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[noparse][[/noparse]0] := 2
MyArray[noparse][[/noparse]1] := 4
MyArray[noparse][[/noparse]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.
MyArray[noparse][[/noparse]0] := 2
MyArray[noparse][[/noparse]1] := 4
MyArray[noparse][[/noparse]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.
Comments
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
You can also write
"0" rather than 48
and
"9" rather than 57
which makes it more readable!
OBJ
· fmt: "Format"
VAR
· long i
· long j[noparse][[/noparse]0]
· byte value[noparse][[/noparse]4]
PUB
· value[noparse][[/noparse]0] = "2"· 'simulate a number as string
· value[noparse][[/noparse]1] = "4"
· value[noparse][[/noparse]2] = "1"
· value[noparse][[/noparse]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[noparse][[/noparse]0] will hold 241
but in this case atoi is simpler.
regards peter
surround your code with [noparse][[/noparse] code ] [noparse][[/noparse] /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
Post Edited (deSilva) : 1/11/2008 11:24:05 PM GMT
Again, I love it Peter!
(Oh, and thanks Phil for the formatter!)