From d4a7938369ccf39639c3fac8f6efa9df42af8168 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Sat, 7 Jan 2023 17:32:49 +0800 Subject: [PATCH] feat: common code from string --- klotski/common_code.cc | 23 ++++++++++++++++++++++- klotski/common_code.h | 2 +- klotski/main.cc | 7 +++++-- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/klotski/common_code.cc b/klotski/common_code.cc index 83374ae..52a50aa 100644 --- a/klotski/common_code.cc +++ b/klotski/common_code.cc @@ -11,7 +11,7 @@ std::string CommonCode::code_to_string(uint64_t common_code, bool shorten) { if (!CommonCode::check(common_code)) { throw std::invalid_argument("invalid common code"); } - char result[10]; + char result[10]; // max length 9-bits sprintf(result, "%09lX", common_code); if (shorten) { // remove `0` after common code if (common_code == 0x000000000) { @@ -22,6 +22,27 @@ std::string CommonCode::code_to_string(uint64_t common_code, bool shorten) { return result; } +uint64_t CommonCode::code_from_string(const std::string &common_code) { + if (common_code.length() > 9 || common_code.length() == 0) { + throw std::invalid_argument("common code format error"); + } + uint64_t result = 0; + for (auto const &bit : common_code) { + result <<= 4; + if (bit >= '0' && bit <= '9') { // 0 ~ 9 + result |= (bit - 48); + } else if (bit >= 'A' && bit <= 'Z') { // A ~ Z + result |= (bit - 55); + } else if (bit >= 'a' && bit <= 'z') { // a ~ z + result |= (bit - 87); + } else { + throw std::invalid_argument("common code format error"); + } + } + // TODO: should we ensure that common code is valid? + return result << (9 - common_code.length()) * 4; // low-bits fill with zero +} + bool CommonCode::check(uint64_t common_code) { uint32_t head = common_code >> 32; if (head >= 16 || (head & 0b11) == 0b11) { // check 2x2 block address diff --git a/klotski/common_code.h b/klotski/common_code.h index 833adc8..430dcea 100644 --- a/klotski/common_code.h +++ b/klotski/common_code.h @@ -6,6 +6,6 @@ class CommonCode { public: static bool check(uint64_t common_code); -// static uint64_t code_from_string(const std::string &common_code); + static uint64_t code_from_string(const std::string &common_code); static std::string code_to_string(uint64_t common_code, bool shorten = false); }; diff --git a/klotski/main.cc b/klotski/main.cc index b73f139..15d4ad3 100644 --- a/klotski/main.cc +++ b/klotski/main.cc @@ -32,8 +32,11 @@ int main() { // std::cout << ShortCode::code_from_string("EP4HZ") << std::endl; - std::cout << CommonCode::code_to_string(0x4FEA13400, true) << std::endl; - std::cout << CommonCode::code_to_string(0x4FEA13400) << std::endl; +// std::cout << CommonCode::code_to_string(0x4FEA13400, true) << std::endl; +// std::cout << CommonCode::code_to_string(0x4FEA13400) << std::endl; + + printf("%09lX\n", CommonCode::code_from_string("4FEa134")); + printf("%09lX\n", CommonCode::code_from_string("1A9bf0C0")); return 0; }