Advertisement
theTANCO

Base Conversion || Convert.cpp

Feb 16th, 2023 (edited)
762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. // main.cpp https://pastebin.com/vV3VfRGF
  2. // Convert.h https://pastebin.com/39AvSGaj
  3.  
  4. #include "Convert.h"
  5.  
  6. Convert::Convert(){
  7.     _base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  8. }
  9.  
  10. // Converts a number from any base (binary, hex, etc.) to a decimal (base 10) number.
  11. int Convert::tonumber(string input, int base){
  12.     int num = 0;
  13.     for(int i = 0; i < input.length(); i++){
  14.         for(int b = 0; b < base; b++){
  15.             if(input[i] == _base[b]){
  16.                 num += b * pow(base, input.length() - i - 1);
  17.                 break;
  18.             }
  19.         }
  20.     }
  21.     return num;
  22. }
  23.  
  24. // Converts a decimal (base 10) number to a number of any base (binary, hex, etc.).
  25. string Convert::tobase(int input, int base){
  26.     string num = "";
  27.     do{
  28.         num = _base[input % base] + num;
  29.         input = floor(input / base);
  30.     }while(input > 0);
  31.     return num;
  32. }
  33.  
  34. // Gets the number of characters available with the given base size.
  35. string Convert::getBase(int baseSize){
  36.     string base = _base.substr(0, baseSize);
  37.     return base;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement