0

I have to string variables

A = 'AA';
B = 'A';

Any suggestions for creating algorithm to subtract two Hexadecimal numbers? First numbers is always greater. so A-B gives result 'A0';

A = 'AA';
B = 'B';

So result is '9F'

I may think of switch-case possibility, but can't solve this out

waplet
  • 151
  • 1
  • 9
  • 1
    1. Convert to numbers, 2. subtract, 3. convert to string. Done. – Jongware May 20 '14 at 09:44
  • It's a bit unclear why you would not do the subtraction on numeric types. Hoverwer, you could implement some kind of nibble full-subtractor which takes borrow into account and would operate on characters. – Codor May 20 '14 at 09:48
  • Cause strings can be a lot longer than just normal integer number – waplet May 20 '14 at 11:24
  • possible duplicate of [Convert hex str to decimal value in delphi](http://stackoverflow.com/questions/13841972/convert-hex-str-to-decimal-value-in-delphi) – xmojmr May 20 '14 at 16:13

1 Answers1

1

If you want to this pure by string logic, without converting to decimal, you need to start to scan both strings from the back, reading one digit from both string at a time(and writing one digit to result), maintain a carry to add to the next etc.

Of course you need to take care for inequal lengths there, and also make sure you set the output length correctly. (or reverse the result)

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
  • Used this method with reversed integer only array and with additional variable for storing value of Minus value of field, so to subtract it from next number. Have already made it working, when subtracting larger from smaller number! – waplet May 22 '14 at 21:27