Advertisement
AntonioVillanueva

Decimal ->Binario

Sep 13th, 2018
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. //Traductor decimal binario Antonio Villanueva
  2. #include <iostream>
  3. #include <cmath>
  4. using namespace std;
  5. #define MIN 0
  6. #define MAX 255
  7.  
  8. /*----------------------------------------------------------------------*/
  9. string binario(int decimal){//calculo binario
  10.     string bin("");//cadena representa binario
  11.     int exp(0);//exponente maximo 2^exp en el rango del numero decimal
  12.    
  13.     while (pow(2,++exp) <=decimal) {};//Maxima potencia de 2 relativa al numero
  14.  
  15.     while (exp>=0){bin+= (decimal & (int)(pow(2,exp--)) ) ? "1" :"0";}//and ultimo bit}
  16.    
  17.     return bin;
  18. };
  19. /*----------------------------------------------------------------------*/
  20. /*----------------------------------------------------------------------*/
  21. int main (){
  22.     for (int decimal=MIN ;decimal<=MAX;decimal++){     
  23.         cout <<"num =" <<decimal<< " bin= "<< binario(decimal)<<endl;
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement