C++如何实现BCD码和ASCII码互转
#include<iostream> #include<stdlib.h> #include<string> using namespace std; string ASCII2BCD(const string &str) { string res; size_t nBegin = 0; int nTemp; char szBuf[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; } string BCD2ASCII(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); else res.push_back('0' + temp); temp = str[i] & 0x0F; if (temp >= 10) res.push_back('A' + temp - 10); else res.push_back('0' + temp); } return res; } int main() { string str1 = BCD2ASCII("王通"); //BCD转ASCII for (int i = 0; i < str1.length(); i++) { cout << str1[i]; } cout << endl; string str2 = ASCII2BCD(str1); //ASCII转BCD for (int i = 0; i < str2.length(); i++) { cout << str2[i]; } cout << endl; return 0; }
运行效果如下:
总结
到此这篇关于C++如何实现BCD码和ASCII码互转的文章就介绍到这了,更多相关C++实现BCD码和ASCII码互转内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)