SHARE
TWEET

Untitled

a guest Aug 13th, 2017 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. char* dec2bin(const int size, int dec) {
  2.     char *bin = new char[size+1];
  3.     int  remain=0, i, how, cur;
  4.     bool finished = false;
  5.     for(i=size; i>=1; i--) {
  6.         if (finished) {
  7.             bin[size-i] = '0';
  8.         } else {
  9.             how = (double)pow((double)2, int(i-1));
  10.             cur = dec - how;
  11.             if (cur >= 0) {
  12.                 dec = cur;
  13.                 bin[size-i] = '1';
  14.                 if (cur==0) {
  15.                     finished = true;
  16.                 }
  17.             } else {
  18.                 bin[size-i] = '0';
  19.             }
  20.         }
  21.     }
  22.     bin[size] = '\0';
  23.     return bin;
  24. }
  25.  
  26. std::cout << "20=0b" << dec2bin(6, 20) << std::endl;
RAW Paste Data
Top