encode/number: add number decoding for base36
This commit is contained in:
parent
5fedbdbdfe
commit
8047bf0f83
@ -247,6 +247,7 @@ list (
|
||||
cpuid_x86.hpp
|
||||
debug.cpp
|
||||
debug.hpp
|
||||
encode/number.hpp
|
||||
encode/base.cpp
|
||||
encode/base.hpp
|
||||
endian.cpp
|
||||
@ -531,6 +532,7 @@ if (TESTS)
|
||||
colour
|
||||
comparator
|
||||
coord
|
||||
encode/number
|
||||
encode/base
|
||||
endian
|
||||
exe
|
||||
|
34
encode/number.hpp
Normal file
34
encode/number.hpp
Normal file
@ -0,0 +1,34 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
*
|
||||
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "../view.hpp"
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
namespace cruft::encode {
|
||||
template <typename ValueT>
|
||||
ValueT
|
||||
decode36 (cruft::view<char const*> &src)
|
||||
{
|
||||
ValueT accum = 0;
|
||||
for (auto const i: src) {
|
||||
accum *= 36;
|
||||
|
||||
switch (i) {
|
||||
case '0'...'9': accum += i - '0'; continue;
|
||||
case 'a'...'z': accum += i - 'a' + 10; continue;
|
||||
case 'A'...'Z': accum += i - 'A' + 10; continue;
|
||||
default:
|
||||
throw std::invalid_argument ("invalid character");
|
||||
}
|
||||
}
|
||||
|
||||
return accum;
|
||||
}
|
||||
}
|
28
test/encode/number.cpp
Normal file
28
test/encode/number.cpp
Normal file
@ -0,0 +1,28 @@
|
||||
#include "encode/number.hpp"
|
||||
#include "tap.hpp"
|
||||
|
||||
|
||||
int main ()
|
||||
{
|
||||
static struct {
|
||||
char const *str;
|
||||
unsigned value;
|
||||
} const TESTS[] = {
|
||||
{ "0", 0 },
|
||||
{ "a", 10 },
|
||||
{ "A", 10 },
|
||||
{ "10", 36 },
|
||||
{ "11", 37 },
|
||||
{ "bfi0", 533304 },
|
||||
{ "15bfi0", 69397560 },
|
||||
};
|
||||
|
||||
cruft::TAP::logger tap;
|
||||
|
||||
for (auto const &t: TESTS) {
|
||||
cruft::view src (t.str);
|
||||
tap.expect_eq (cruft::encode::decode36<unsigned> (src), t.value, "base36 decode '%!'", t.str);
|
||||
}
|
||||
|
||||
return tap.status ();
|
||||
}
|
Loading…
Reference in New Issue
Block a user