Advertisement
jacknpoe

Retorna string para inteiros em bases de 2 a 10

Dec 14th, 2013 (edited)
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstring>
  3.  
  4. char tam_base_2_a_10( 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_10( 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 > 10){
  24.         strcpy( buffer, (char*) "a base nao pode ser maior que 10");
  25.         return;
  26.     }
  27.  
  28.     tam = tam_base_2_a_10( 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.         buffer[tam] = temp + '0';
  42.     }
  43.  
  44.     return;
  45. }
  46.  
  47. int main( void){
  48.     char resultado[50];
  49.     unsigned int valor = 0;
  50.     int base = 2;
  51.  
  52.     std::cout << "Entre com o valor: ";
  53.     std::cin >> valor;
  54.  
  55.     std::cout << "Entre com a base: ";
  56.     std::cin >> base;
  57.  
  58.     int_base_2_a_10( valor, base, resultado);
  59.  
  60.     std::cout << "\nResultado: " << resultado << "\n";
  61. }
Tags: base
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement