[SOLVED] string to BCD and back again

Status
Not open for further replies.

bwend

Newbie level 2
Joined
Apr 19, 2011
Messages
2
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,293
I have a C programming task to do, and need some assistance with this part.
I have a string, for example: 02e0

I need to convert this string to BCD, then back into its original format, by subtracting '0' and shifting.

I run into problems when hitting the 'e', my method sees this:
101 - 48, and hence stores '5' (decimal 53). However I need to retrieve this character back as its original hex 'e' value.

Does anyone have any suggestions?
 

the +-48 trick is used with numbers because it can convert a value 0-9 to a char representation 0-9 and vice versa,
you are obviously trying to convert a hex value of 0-15 (0-f) to the char 0-9 and a-f and vice versa.
You can use a condition that checks if the number is <=57 (which is char 9) and if true subtract the value 48 ,
if false then you have to subtract 55 so that a becomes 10, b 11 etc.

Then use a condition in the reverse direction too, if <=9 then add 48 else add 55.

Alex

---------- Post added at 21:28 ---------- Previous post was at 21:20 ----------

One small correction, +-55 is for letters A-F , for a-f you have to use +-87

Alex
 
Reactions: bwend

    bwend

    Points: 2
    Helpful Answer Positive Rating
Ah yes, another 'Doh!' moment. Thank you for your succinct (and absolutely correct) reply.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…