I have two strings which are hex value for some number now I want to add them and want the result in the hex values which is also a string.
-
http://stackoverflow.com/questions/3648411/objective-c-parse-hex-string-to-integer + http://stackoverflow.com/questions/16706846/convert-integer-to-hexadecimal ? – Larme Apr 18 '17 at 11:38
1 Answers
It is unclear what is important in your question: you could have been given the task of implementing "string addition" (maybe a student assignment?); or you could simply have two numbers which are represented as strings and need to form their sum and represent it as a string.
In the first case you need to loop over the two strings a character at a time, produce the digit sum, calculate the carry, etc. For checking a character is a valid hex digit and converting it into a value you can sum you should look at the functions isxdigit()
, ishexnumber()
and digittoint()
- all these are part of the standard (Objective-)C library and the documentation can be found using the man
command in the Terminal. For computing the sum and carry you will find the modulus operator, %
, useful or you could consider using div()
. To convert your individual digit sum back to a character you can use a string of hex digit characters and simply index into it.
In the second case you can stick with Objective-C framework classes: NSScanner
provides methods to parse hex numbers; and NSString
's stringWithFormat:
enables you to convert a number to a hex representation. In this case addition is just the normal operator, +
, as the numbers are in standard internal format (i.e. binary bits).
If you have trouble implementing either approach ask a new question, showing your code and describing your issue, and someone will undoubtedly help you.
HTH

- 52,522
- 5
- 70
- 86