Abstracted Base10_2_X to work with arbitrary containers and digit-types
This commit is contained in:
parent
6e62b312ce
commit
50957fb9a3
@ -1,15 +1 @@
|
||||
#include "GeneralUtility.h"
|
||||
#include <string>
|
||||
|
||||
std::string GeneralUtility::Base10_2_X(const std::uint64_t &num, const std::string &set, const std::uint32_t minOutLen) {
|
||||
// Convert num to a string
|
||||
std::stringstream ss;
|
||||
ss << num;
|
||||
const std::string numStr = ss.str();
|
||||
|
||||
// Use BaseX_2_Y to convert to outbase
|
||||
const std::string convertedNum = BaseX_2_Y<std::string, std::string>(numStr, "0123456789", set, minOutLen);
|
||||
|
||||
// return it
|
||||
return convertedNum;
|
||||
}
|
||||
|
@ -38,7 +38,8 @@ public:
|
||||
//! \param num The number to be converted
|
||||
//! \param set The desired set/base for the output to be in
|
||||
//! \return `num` in base `set`
|
||||
static std::string Base10_2_X(const std::uint64_t& num, const std::string& set, const std::uint32_t minOutLen = 1);
|
||||
template <class T_Container>
|
||||
static T_Container Base10_2_X(const std::uint64_t& num, const T_Container& set, const std::uint32_t minOutLen = 1);
|
||||
|
||||
//! Will convert a number from an arbitrary base to another arbitrary base.
|
||||
//! \param num A string representation of a number
|
||||
@ -218,4 +219,18 @@ T_ContainerOut GeneralUtility::BaseX_2_Y(const T_ContainerIn& num, const T_Conta
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class T_Container>
|
||||
T_Container GeneralUtility::Base10_2_X(const std::uint64_t &num, const T_Container& set, const std::uint32_t minOutLen) {
|
||||
// Convert num to a string
|
||||
std::stringstream ss;
|
||||
ss << num;
|
||||
const std::string numStr = ss.str();
|
||||
|
||||
// Use BaseX_2_Y to convert to outbase
|
||||
const T_Container convertedNum = BaseX_2_Y<std::string, T_Container>(numStr, "0123456789", set, minOutLen);
|
||||
|
||||
// return it
|
||||
return convertedNum;
|
||||
}
|
||||
|
||||
#endif //GENERALUTILITY_GENERALUTILITY_H
|
||||
|
@ -75,3 +75,23 @@ TEST_CASE(__FILE__"/TestPadding", "[Base10_2_X]")
|
||||
// Verify
|
||||
REQUIRE(out == expected_out);
|
||||
}
|
||||
|
||||
// Tests that conversion with more complex 'digits' works. Weird-ass usecase
|
||||
TEST_CASE(__FILE__"/BaseWeird_to_10", "[Base10_2_X]")
|
||||
{
|
||||
// Setup
|
||||
|
||||
// Yes... That is actually our base...
|
||||
const std::vector<std::string> set = { "Banana", "Apple", "Peach", "Strawberry", "Tomato", "Cherry" };
|
||||
|
||||
const std::uint64_t in = 69;
|
||||
|
||||
// Yes, that is a fucking number. It's 69 in whatever the fuck that base is
|
||||
const std::vector<std::string> expected_out = { "Apple", "Cherry", "Strawberry" };
|
||||
|
||||
// Exercise
|
||||
const std::vector<std::string> out = GeneralUtility::Base10_2_X(in, set);
|
||||
|
||||
// Verify
|
||||
REQUIRE(out == expected_out);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user