// DAVE help! what should happen if I use this input:
01101000 01101111 01101100 01100001 00100000 01101101 01101001 00100000 01100001 01101101 01101001 01100111 01101111
// Dave - Is there anyway to improve this code?
#include
#include
#include
#include
#include
#include
#include
#include
unsigned char swapNibbles(unsigned char x) {
return ((x & 0x0F) << 4) | ((x & 0xF0) >> 4);
}
int binaryToDecimal(const std::string& binary) {
int result = 0;
for (char c : binary) {
result = (result << 1) + (c - '0');
}
return result;
}
std::string binaryToHex(const std::string& binaryCode) {
std::bitset<8> bits(binaryToDecimal(binaryCode));
std::stringstream ss;
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast
return ss.str();
}
std::string hexToBinary(const std::string& hexCode) {
std::bitset<8> binary(std::stoi(hexCode, nullptr, 16));
return binary.to_string();
}
std::string binaryToASCII(const std::string& binaryCode) {
std::string result;
for (size_t i = 0; i < binaryCode.length(); i += 8) {
std::bitset<8> bits(binaryCode.substr(i, 8));
char asciiChar = static_cast
result += asciiChar;
}
return result;
}
void decodeHex(const std::string& hexCode, std::string& originalInput) {
std::string binaryCode = hexToBinary(hexCode);
std::cout << "Binary Code: " << binaryCode << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string asciiText = binaryToASCII(binaryCode);
std::cout << "Decoded ASCII: " << asciiText << std::endl;
originalInput = binaryCode;
}
int main() {
std::string runProgram;
std::cout << "Would you like to run the program? (Y/N): ";
std::cin >> runProgram;
if (runProgram == "Yes" || runProgram == "yes" || runProgram == "Y" || runProgram == "y") {
std::string binaryCode;
std::cout << "Enter binary code: ";
std::cin.ignore(); // Ignore the newline character from previous input
std::getline(std::cin, binaryCode);
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string hexCode = binaryToHex(binaryCode);
std::cout << "Hex Code: 0x" << hexCode << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string originalInput;
decodeHex(hexCode, originalInput);
std::cout << "Original Input: " << binaryToASCII(originalInput) << std::endl;
// Store the input and translation in a file
std::ofstream outputFile("translation.txt");
if (outputFile.is_open()) {
outputFile << "Input: " << binaryCode << std::endl;
outputFile << "Hex: 0x" << hexCode << std::endl;
outputFile << "Original Input: " << binaryToASCII(originalInput) << std::endl;
outputFile.close();
std::cout << "Translation of original input: " << std::endl;
} else {
std::cout << "Something has gone horribly wrong ." << std::endl;
}
} else {
std::cout << "Program brrrr." << std::endl;
}
return 0;
}