I'm maintenancing an old project with Delphi 7. I need to convert a long hexadecimal string to a decimal string. I searched and found sample code in C# but not in Delphi. I only have two options:
- Implement or use a function in Delphi 7.
- Implement or use a function in Delphi 2010 then export it as DLL.
Maximum length of hex string I'm working on is 40 character, here is a sample :
'6F000080B4D4B3426C66A655010001000080B4'
I used rapidtables to do conversion and here it's output
'2475382888117010136950089026926167642744062132'
I hope that some one has solved this problem before and can help. Maybe someone give me an algorithm I can use to write a function in Delphi.
Note :
In Delphi 7 for Int64 the maximum positive value is $7FFFFFFFFFFFFFFF = 9223372036854775807 and this value is far from what I need.
For this to solve we need to cut it down into three steps:
As tiny helpers which are needed in the other functions let me have these:
Addition
We all learnt written addition in school: write all numbers in one row, then add each row's digits and carry that sum's additional digits over to the next row of digits of the summands. This can also be done easily:
I did not restrict it to always 2 summands for the following reasons:
$30is the ASCII code for the character'0'- subtracting the potential character'0'to'9'by that of'0'gives us the value0to9.Multiplication
We all learnt written multiplication in school, too: for each digit of one factor calculate that product (which can only be an "easy" multiplication by 0 to 9), write down all those products in a row as per digit position (optionally with trailing zeroes), then add all those products into a sum (referencing written addition). This can also be done easily, since we now have solved addition already:
It could have been even shorter, since
Summe()can already deal with 0 and 1 summands - I don't really need to treat that differently. As previously told: the easy multiplication is done by simple addition - not very performance efficient, but easy to comprehend.Hexadecimal to decimal conversion
Since we can now add and multiply, we're also able to convert each digit of a non-decimal-base number and increase the outcome to the overall result:
It even works not only for hexadecimal (base 16) input, but also for others.
$41is the ASCII value for'A'- subtracting the potential characters'A'to'Z'by that of'A'gives us the value0to25, to which we then just add10.Tests
Strings are implied. Spaces are just for optical reasons.
Summe()Summe()Produkt()Produkt()ConvertToDecimal()Summary
0, but a result of0is not reduced to an empty String either.AnsiString,UnicodeString,WideStringand so on. However,Charis used as type, which is bound to that choice. But the functionsChr()andOrd()should support everything again.