From 052938f6cb565ab4744c854888e8f3412a897940 Mon Sep 17 00:00:00 2001 From: daleclack Date: Mon, 29 May 2023 10:52:44 +0800 Subject: [PATCH] Add string to binary source code --- cpp/string_to_bin.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 cpp/string_to_bin.cpp diff --git a/cpp/string_to_bin.cpp b/cpp/string_to_bin.cpp new file mode 100644 index 0000000..5cea052 --- /dev/null +++ b/cpp/string_to_bin.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +int main(int argc, char **argv) +{ + char str[70], tmp2[8]; + std::cin >> str; // Input the sentence + + std::fstream outfile; + outfile.open("20comm_exp1_bs.dat", std::ios::out); // Open the file + + for (int i = 0; i < strlen(str); i++) + { + int temp = str[i]; + for (int j = 8; j > 0; j--) + { // Convert ASCII to 8 bit binary + tmp2[j - 1] = temp % 2 + '0'; + temp /= 2; + } + for (int j = 0; j < 8; j++) + { // Output the binary + std::cout << tmp2[j] << " "; + if (outfile.is_open()) + { // Output the data to file + outfile << tmp2[j] << " "; + } + } + } + outfile << std::endl; + outfile.close(); // Close the file, the content will be saved + return 0; +} \ No newline at end of file