Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // BaseConverter.h: interface for the CBaseConverter class.
- //
- //////////////////////////////////////////////////////////////////////
- #if !defined(AFX_BASECONVERTER_H__28149E41_2127_11D7_A179_000103DD18CD__INCLUDED_)
- #define AFX_BASECONVERTER_H__28149E41_2127_11D7_A179_000103DD18CD__INCLUDED_
- #if _MSC_VER > 1000
- #pragma once
- #endif // _MSC_VER > 1000
- # include <string>
- # include <cassert>
- # include <algorithm>
- # include <cmath>
- using std::string;
- namespace NO5
- {
- namespace Math
- {
- class CBaseConverter
- {
- // returns -1 if its not a valid character
- static int GetDecValue(char c)
- {
- int res = -1;
- if( c >= '0' && c <= '9'){
- res = (int(c) - int('0'));
- }
- else if(c >= 'A' && c <= 'Z'){
- res = (int(c) - int('A'));
- res += 10;
- }
- else if(c >= 'a' && c <= 'z'){
- res = (int(c) - int('a'));
- res += 10;
- }
- return res;
- }
- static char GetBaseXDigit(unsigned int i,bool UpCase =\
- true)
- {
- char res;
- if(i >= 0 && i <= 9){
- res = char(int('0') + i);
- }
- else if(i < 36){
- if(UpCase){
- res = char(int('A') + i - 10);
- }
- else{
- res = char(int('a') + i - 10);
- }
- }
- else{
- assert(0);
- // throw something;
- }
- return res;
- }
- static bool IsBaseXDigit(char c,unsigned int b)
- {
- int dec = GetDecValue(c);
- return (dec > 0 && dec < b);
- }
- public:
- // returns -1 if value is not valid
- static int FromBaseX(const string &value,unsigned\
- int b)
- {
- int res = 0;
- const string::size_type len = value.length();
- string::size_type i;
- int tmp;
- for(i=0;i<len;i++){
- tmp = GetDecValue(value[len - i - 1]);
- if(tmp < 0){
- res = -1;
- break;
- }
- res += tmp * ( pow(b,i));
- }
- return res;
- }
- static string ToBaseX(unsigned int value,unsigned int b,
- bool UpCase = true)
- {
- unsigned int q,r;
- string res;
- q = value;
- while(q != 0){
- r = q % b;
- q = q / b;
- res += GetBaseXDigit(r,UpCase);
- }
- std::reverse(res.begin(),res.end());
- return res;
- }
- static string BaseXtoY(const string &value,unsigned int\
- b_x,unsigned int b_y,bool bUpCase = true)
- {
- string res;
- if(b_x == b_y)
- res = value;
- else
- res = ToBaseX(FromBaseX(value,b_x),b_y,bUpCase);
- return res;
- }
- };
- }
- }
- #endif // !defined(AFX_BASECONVERTER_H__28149E41_2127_11D7_A179_000103DD18CD__INCLUDED_)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement