Advertisement
jacknpoe

Retorna string para inteiros em bases de 2 a 36

Feb 25th, 2024
752
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | Source Code | 0 0
  1. #include<iostream>
  2. #include<cstring>
  3.  
  4. char tam_base_2_a_36( unsigned long valor, int base){
  5.     char temp = 0;
  6.  
  7.     while( valor > 0){
  8.         temp++;
  9.         valor /= base;
  10.     }
  11.  
  12.     return temp;
  13. }
  14.  
  15. void int_base_2_a_36( unsigned long valor, int base, char* buffer){
  16.     char temp, tam;
  17.  
  18.     if( base < 2){
  19.         strcpy( buffer, (char*) "a base nao pode ser menor que 2");
  20.         return;
  21.     }
  22.    
  23.     if( base > 36){
  24.         strcpy( buffer, (char*) "a base nao pode ser maior que 36");
  25.         return;
  26.     }
  27.  
  28.     tam = tam_base_2_a_36( valor, base);
  29.  
  30.     if( tam == 0) {
  31.         buffer[0] = '0'; buffer[1] = 0;
  32.         return;
  33.     }
  34.  
  35.     buffer[ tam] = 0;
  36.  
  37.     while( valor > 0){
  38.         temp = valor % base;
  39.         valor /= base;
  40.         tam -= 1;
  41.         if(temp < 10) {
  42.             buffer[tam] = temp + '0';
  43.         } else {
  44.             buffer[tam] = temp + 'A' - 10;
  45.         }
  46.     }
  47.  
  48.     return;
  49. }
  50.  
  51. int main( void){
  52.     char resultado[50];
  53.     unsigned int valor = 0;
  54.     int base = 2;
  55.  
  56.     std::cout << "Entre com o valor: ";
  57.     std::cin >> valor;
  58.  
  59.     std::cout << "Entre com a base: ";
  60.     std::cin >> base;
  61.  
  62.     int_base_2_a_36( valor, base, resultado);
  63.  
  64.     std::cout << "\nResultado: " << resultado << "\n";
  65. }
Tags: base
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement