In: Computer Science
Can you convert this code (Python) to C++
def decrypt(message, key): decryptedText = "" for i in message: M = ord(i) k = int(key, 16) xor = M ^ k decryptedText += chr(xor) return decryptedText def encrypt(message, key): encryptedText = "" for i in message: M = ord(i) k = int(key, 16) xor = M ^ k encryptedText += chr(xor) return encryptedText # main function userText = input("Enter text: ") userKey = str(input("Enter a key: ")) encryptedMessage = encrypt(userText, userKey) decryptedMessage = decrypt(encryptedMessage, userKey) print("Encrypted message: ", encryptedMessage) print("Decrypted message: ", decryptedMessage)
Converted C++ code:
#include <bits/stdc++.h>
using namespace std;
// function to decrypt the message
string decrypt(string message, string key){
string decryptedText = "";
int k = 0;
reverse(key.begin(), key.end());
for (int i = 0; i < key.size(); i++){
k += (key[i] - '0') * pow(16, i);
}
for (char &i: message){
int M = (int) i;
int _xor = M ^ k;
string s(1, static_cast<char>(_xor));
decryptedText += s;
}
return decryptedText;
}
// function to encrypt the message
string encrypt(string message, string key){
string encryptedText = "";
int k = 0;
reverse(key.begin(), key.end());
for (int i = 0; i < key.size(); i++){
k += (key[i] - '0') * pow(16, i);
}
for (char &i: message){
int M = (int) i;
int _xor = M ^ k;
string s(1, static_cast<char>(_xor));
encryptedText += s;
}
return encryptedText;
}
// Main function
int main(){
// Take input
string userText, userKey;
cout << "Enter text: "; cin >> userText;
cout << "Enter a key: "; cin >> userKey;
// Call the functions
string encryptedMessage = encrypt(userText, userKey);
string decryptedMessage = decrypt(encryptedMessage, userKey);
// Print the output
cout << "Encrypted message: " << encryptedMessage << endl;
cout << "Decrypted message: " << decryptedMessage << endl;
return 0;
}
Please refer to the following pictures for the source code:
Sample execution of the above code: