#include <iostream> // 引入輸出輸入的標準函式庫
#include <bitset> // 引入 bitset 函式庫,用來處理二進制數字
int main()
{
// 標準的 Hello World 輸出
std::cout << "Hello, World!" << std::endl; // 輸出 "Hello, World!" 並換行
std::cout << "Hello, World!"; // 輸出 "Hello, World!" 但不換行
std::cout << "Hello, World!" << std::endl; // 再次輸出 "Hello, World!" 並換行
// 範例:自訂訊息的輸出
std::string msg = "Hello, Aucer"; // 宣告字串變數 msg 並指定其值為 "Hello, Aucer"
std::cout << msg << std::endl; // 輸出 msg 的內容並換行
// 範例:輸出字串與數字
int age = 2025; // 宣告整數變數 age 並賦值為 2025
std::cout << msg << age << std::endl; // 輸出 msg 與 age 並換行
std::cout << msg << " " << age << std::endl; // 輸出 msg、空格與 age,並換行
// 記憶體單位的說明
// 1 GB 是 1024 MB(Gigabyte 到 Megabyte)
// 1 MB 是 1024 KB(Megabyte 到 Kilobyte)
// 1 byte 是 8 bits(Byte 到 Bit)
// 1 bit 是 0 或 1(最小的資料單位)
// 顯示 "Hello, World!" 的二進制表示
std::cout << "This is how to show [Hello, World!] in 0 and 1 in binary format:" << std::endl;
// 將字串 "Hello, World!" 轉換為二進制格式並顯示
std::string sentence = "Hello, World!"; // 設定要轉換的句子
for (char c : sentence) { // 遍歷每一個字符
// 將每個字符轉換為二進制並輸出
std::cout << c << " = " << std::bitset<8>(c) << std::endl; // 使用 bitset 將字符轉為 8 位元二進制
}
// 解釋
std::cout << "\nExplanation:" << std::endl;
std::cout << "Each letter, space, and punctuation mark is represented by a unique 8-bit binary number." << std::endl;
std::cout << "The binary representation differs between uppercase and lowercase letters, spaces, and punctuation marks." << std::endl;
std::cout << "For example:" << std::endl;
std::cout << " - 'H' is 01001000, but 'h' is 01101000 (notice the difference)." << std::endl;
std::cout << " - The comma ',' has the binary value 00101100, while the exclamation mark '!' is 00100001." << std::endl;
std::cout << " - A space character is represented as 00100000, which is different from any letter or punctuation." << std::endl;
return 0; // 結束程式
}
C++ 筆記(2)-單位與二進制
Tags: