// Function to encrypt a string to decimal
unsigned long encrypt_string_to_decimal(const char* input_str) {
    unsigned long decimal_values_concatenated = 0;  // Initialize as integer
    int i = 0;
    while (input_str[i] != '\0') {
        int ascii_value = input_str[i];  // Convert character to ASCII value
        // Ensure each ASCII value is represented by three digits with leading zeros
        if (ascii_value < 100) {
            decimal_values_concatenated = decimal_values_concatenated * 1000 + 100 + ascii_value; // Add 100 as padding
        } else {
            decimal_values_concatenated = decimal_values_concatenated * 1000 + ascii_value;
        }
        i++;
    }
    return decimal_values_concatenated;
}

// Function to decrypt a decimal value to a string
String decrypt_decimal_to_string(unsigned long decimal_value) {
    String decrypted_string = "";
    while (decimal_value > 0) {
        int ascii_value = decimal_value % 1000;  // Extract the last three digits
        // Remove the padding if present
        if (ascii_value >= 100) {
            ascii_value -= 100;
        }
        char ascii_char = (char)ascii_value;  // Convert ASCII value to character
        decrypted_string = String(ascii_char) + decrypted_string;  // Prepend the character to the decrypted string
        decimal_value /= 1000;  // Move to the next set of three digits
    }
    return decrypted_string;
}

// Function to read input from Serial Monitor, encrypt it, and display the result
void encryptInput() {
    String input_string = Serial.readStringUntil('\n'); // Read input string from Serial Monitor
    unsigned long encrypted_value = encrypt_string_to_decimal(input_string.c_str()); // Encrypt the input string
    Serial.print("Encrypted value: ");
    Serial.println(encrypted_value); // Display the encrypted value
}

// Function to read input from Serial Monitor, decrypt it, and display the result
void decryptInput() {
    unsigned long encrypted_value = Serial.parseInt(); // Read input as integer from Serial Monitor
    String decrypted_string = decrypt_decimal_to_string(encrypted_value); // Decrypt the input value
    Serial.print("Decrypted string: ");
    Serial.println(decrypted_string); // Display the decrypted string
}

void setup() {
    Serial.begin(9600); // Initialize Serial communication
}

void loop() {
    if (Serial.available() > 0) {
        char command = Serial.read(); // Read the first character of input
        if (command == 'e') {
            encryptInput(); // Encrypt input if 'e' is entered
        } else if (command == 'd') {
            decryptInput(); // Decrypt input if 'd' is entered
        }
    }
}