Browse Source

feat: common code from string

master
Dnomd343 2 years ago
parent
commit
d4a7938369
  1. 23
      klotski/common_code.cc
  2. 2
      klotski/common_code.h
  3. 7
      klotski/main.cc

23
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

2
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);
};

7
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;
}

Loading…
Cancel
Save