对字符串的每个字符进行奇校验,将字符串对应的ASCII码值转换为二进制,使1的个数是奇数,如果不是,最高位补1
#include <iostream> #include <string> #include <algorithm> using namespace std; string chartostring(char c) { string str; int num = c; while (num) { str += (num % 2) + '0'; num /= 2; } reverse(str.begin(), str.end()); return str; } // 对字符串的每个字符进行奇校验,将字符串对应的ASCII码值转换为二进制,使1的个数是奇数 int main() { string s; while (cin >> s) { string ans; for (int i = 0; i < s.size(); i++) { ans = chartostring(s[i]); while (ans.size() < 8) { ans.insert(0, 1, '0'); } int cnt = 0; for (int i = 0; i < ans.size(); i++) { if (ans[i] == '1') cnt++; } // 1的个数为偶数,则最高位补1 if (cnt % 2 == 0) { ans[0] = '1'; } cout << ans << endl; } } return 0; }