ฐานสิบเป็นฐานสอง
แปลงจำนวนเต็มบวกฐานสิบเป็นฐานสอง
ฐานสิบเป็นฐานสอง คืออะไร?
การหารด้วยสองซ้ำ ๆ ให้เลขฐานสองจากหลักต่ำสุดไปสูงสุด
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
unsigned number = 13, value = number; int bits[32], count = 0;
// Store remainders generated from right to left.
do { bits[count++] = value % 2; value /= 2; } while (value);
printf("%u = ", number); while (count) printf("%d", bits[--count]); puts("");
}
13 = 1101
C++
main.cpp
#include <bitset>
#include <iostream>
#include <string>
int main() {
unsigned number = 13;
// Remove leading zeroes from a fixed-width bitset string.
std::string bits = std::bitset<32>(number).to_string();
bits.erase(0, bits.find_first_not_of('0'));
std::cout << number << " = " << bits << '\n';
}
13 = 1101
เปรียบเทียบ C และ C++
เก็บเศษไว้แล้วพิมพ์ย้อนกลับ เพราะการหารหาหลักสุดท้ายได้ก่อน
C
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด