1. BCD code to ASC code:
It is relatively simple to convert BCD to ASC, And the bitwise AND shift can be done.
Stringbcd2ascii (const string & Str) {string res; For (size_t I = 0; I <Str. size (); I ++) {char temp = (STR [I]> 4) & 0x0f; If (temp> = 10) res. push_back ('a' + temp-10); elseres. push_back ('0' + temp); temp = STR [I] & 0x0f; If (temp> = 10) res. push_back ('a' + temp-10); elseres. push_back ('0' + temp);} return res ;}
2. ASC code to BCD code:
Use scanf to directly convert two adjacent characters into hexadecimal numbers.
String ascii2bcd (const string & Str) {stringres; size_tnbegin = 0; intntemp; charszbuf [16] = {0}; If (Str. Size () % 2! = 0) {szbuf [0] = '0'; szbuf [1] = STR [0]; sscanf (szbuf, "% x", & ntemp); nbegin = 1; res. push_back (char) ntemp) ;}for (; nbegin <Str. size (); nbegin + = 2) {szbuf [0] = STR [nbegin]; szbuf [1] = STR [nbegin + 1]; sscanf (szbuf, "% x", & ntemp); Res. push_back (char) ntemp);} return res ;}