Interesting problem. You’ve just maxed out the capabilities of PIC basic, which is most happy with 16 bit numbers, but has some facilities to get out 32 bits.
The basic algorithm is simple: Start from the most significant ASCII digit, convert to binary, add the binary to a sum. If more digits, multiply the sum by 10 and repeat for the next digit. Actually, when you implement this you zero out the sum first, then do the times 10 multiply at the top of the loop (saves you the code for checking for the last run of the loop).
Converting ASCII to binary is simple: just subtract $30 (ASCII zero) from the ASCII and you got it!
In the code below we use temp for the binary, and BottomSum and TopSum for the sum. We need 2 words for the sum to get 32 bits. The next trick is to recognize that PBP has 2 different multiplication methods, * and **. When you multiply two 16 bit numbers the result can be as high as 32 bits. PBP handles this by using * to return the lowest 16 bits and ** to return the highest 16 bits. We use both methods to accumulate a 32 bit sum for the times 10 part.
The following code will compile, but has not been properly debugged. Always code defensively when using integer arithmetic where an overflow can give you buggy results.
Code:
ASCII var BYTE[8] ' holds the 8 orgional ASCII digits
HexResult var byte[4] ' place for 8 hex digits (4 bytes)
BottomSum var Word ' BottomSum & TopSum used to store 16
TopSum var word ' bit results
LastBottom var byte ' result of last operation to BottomSum
' used to detect overflows
Index var byte ' pointer
temp var word ' tempory intermediate result
' fill ASCII with data ASCII[]= 31724529
ASCII[0]= 9
ASCII[1]= 2
ASCII[2]= 5
ASCII[3]= 4
ASCII[4]= 2
ASCII[5]= 7
ASCII[6]= 1
ASCII[7]= 3
BottomSum =0
TopSum =0
LastBottom = 0
For Index = 7 to 0 step -1
' first, take total accumlated in the sums and multiply by 10
TopSum = TopSum * 10 ' direct multiply
BottomSum = BottomSum * 10 ' also a direct multiply
TopSum = TopSum + BottomSum ** 10 ' top 16 bits of the multiply
' convert ascii to number,add to accumulated sum
temp = ASCII[Index] - $30 ' convert ascii digit to binary
bottomSum = BottomSum + temp
' check bottom result in case of overflow, if so, bump top result
' ( an overflow will give a result smaller then the existing value)
if bottomSum < Lastbottom then TopSum = TopSum + 1
LastBottom = bottomSum ' set for next iteration
next index
' now we have the result in Top & Bottom Sum, move to HexResult array
HexResult[0] = bottomsum.byte0
HexResult[1] = bottomsum.byte1
HexResult[2] = Topsum.byte0
HexResult[3] = Topsum.byte1
Bookmarks