打印 0~255 所有 ASCII 碼及其對應字符(控制字符顯示 `.`)。
#include
#include
int main() {
printf("Dec Hex Char\n");
printf("---------------\n");
for (int i = 0; i <= 255; i++) {
char display = isprint(i) ? (char)i : '.';
printf("%3d 0x%02X %c\n", i, i, display);
if (i % 16 == 15) puts(""); // 每 16 行分組
}
return 0;
}
void print_ascii_rec(int i) {
if (i > 255) return;
char display = isprint(i) ? (char)i : '.';
printf("%3d 0x%02X %c%s", i, i, display, (i % 16 == 15) ? "\n" : " ");
print_ascii_rec(i + 1);
}
int main() {
print_ascii_rec(0);
return 0;
}
⚠️ 遞歸深度 256 安全(棧幀極小),但**無任何優勢**,純教學用。
int main() {
int i = 0;
while (i <= 255) {
for (int col = 0; col < 16 && i <= 255; col++, i++) {
char c = (i >= 32 && i <= 126) ? i : '.';
printf("%3d:%c ", i, c);
}
puts("");
}
return 0;
}
| 範圍 | 類別 | 典型字符 |
|---|---|---|
| 0-31 | 控制字符 | NUL(0), LF(10), CR(13), ESC(27) |
| 32 | 空格 | ' ' |
| 33-47 | 標點符號 | ! " # $ % & ' ( ) * + , - . / |
| 48-57 | 數字 | 0-9 |
| 58-64 | 標點符號 | : ; < = > ? @ |
| 65-90 | 大寫字母 | A-Z |
| 91-96 | 標點符號 | [ \ ] ^ _ ` |
| 97-122 | 小寫字母 | a-z |
| 123-126 | 標點符號 | { | } ~ |
| 127 | DEL | 刪除 |
| 128-255 | 擴展 ASCII | 視編碼而定 (Latin-1/CP437/GBK...) |
void gen_html_entity_table() {
puts("Dec Hex Char Entity ");
for (int i = 0; i <= 255; i++) {
const char *entity;
switch (i) {
case 34: entity = """; break;
case 38: entity = "&"; break;
case 60: entity = "<"; break;
case 62: entity = ">"; break;
case 160: entity = " "; break;
default: entity = (i >= 32 && i <= 126) ? "—" : "—";
}
char display = (i >= 32 && i <= 126) ? i : ' ';
printf("%d 0x%02X %c %s \n", i, i, display, entity);
}
puts("
");
}
for 迴圈**:簡潔、高效、無棧溢出風險。isprint() (需 ctype.h) 判斷可打印字符,**避免控制字符亂碼/終端異常**。%3d 0x%02X %c 對齊美觀,每 16 行換行對應十六進制直觀。