Created
November 12, 2024 05:52
-
-
Save btnguyen2k/70a69d8880eacbbaf04f5522cd3acd4a to your computer and use it in GitHub Desktop.
[C++] Chuyển số thập nhân sang cơ số 32 - http://goclaptrinh.io/cms/beginner/c-cpp-crockford-base32-numbers/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| int nhapSoThapPhan() { | |
| int n; | |
| std::cout << "Nhập số thập phân: "; | |
| std::cin >> n; | |
| return n; | |
| } | |
| std::string nhapSoBase32() { | |
| std::string s; | |
| std::cout << "Nhập số ở hệ cơ số 32 (bảng mã Crockford Base32): "; | |
| std::cin >> s; | |
| return s; | |
| } | |
| // đổi số thập phân sang cơ số 32 | |
| std::string doiSangBase32(int n) { | |
| std::string base32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; | |
| std::string s; | |
| while (n > 0) { | |
| s = base32[n % 32] + s; | |
| n /= 32; | |
| } | |
| return s; | |
| } | |
| // chuyển 1 ký tự sang số | |
| int charToNum(char c) { | |
| c = std::toupper(c); // chuyển thành ký tự in hoa | |
| switch (c) { | |
| // theo qui định của bảng mã Crockford, chấp nhận ký tự I và L, nhưng chuyển thành số 1 | |
| case 'I': case 'L': | |
| c = '1'; | |
| break; | |
| // theo qui định của bảng mã Crockford, chấp nhận ký tự O, nhưng chuyển thành số 0 | |
| case 'O': | |
| c = '0'; | |
| break; | |
| // theo qui định của bảng mã Crockford, chấp nhận ký tự U, nhưng chuyển thành V | |
| case 'U': | |
| c = 'V'; | |
| break; | |
| } | |
| std::string base32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; | |
| for (int i = 0; i < 32; i++) { | |
| if (c == base32[i]) return i; | |
| } | |
| return -1; | |
| } | |
| // chuyển số ở hệ cơ số 32 sang thập phân | |
| int doiSangThapPhan(std::string s) { | |
| int n = 0; | |
| for (int i = 0; i < s.length(); i++) { | |
| int num = charToNum(s[i]); | |
| if (num == -1) return -1; // có ký tự không hợp lệ! | |
| n = n * 32 + num; | |
| } | |
| return n; | |
| } | |
| int main() { | |
| int n = nhapSoThapPhan(); | |
| std::cout << "Số thập phân " << n << " chuyển sang hệ cơ số 32: " << doiSangBase32(n) << std::endl; | |
| std::string s = nhapSoBase32(); | |
| std::cout << "Số ở hệ cơ số 32 [" << s << "] chuyển sang thập phân: " << doiSangThapPhan(s) << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment