convert (int) Dec to Bin

Hi,
I working a converter from Dec to Bin
(DEC) 5 == (0B101)

must's:
- writing Right to Left (0XF5 == 0B1111 0101)
- compact as possible

future:
- negative numbers
- working with double's and floatings

like's:
- a space every nibble (easy reading (A))


My First code to succeed the MUST's
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int num = 5;
for (int pow = 1;;){ 
  // check for max power coefficient
  pow <<= 1;
  if (pow <= num ) continue;
  
  int binary = 0;
  binary:
  // count down from highest power
  pow >>= 1;
  if (pow >= 1 ) {   
    int bit = (((num-pow)<0) ? 0 : 1);
    if (bit == 1) num -= pow;
    binary = (binary*10) + bit;
    goto binary;
  }
  num = binary;
  break;
}
cout << dec << "[0B" << num << ']' << endl;


[b]any suggestions to upgrade this code ?[/b]
closed account (o1vk4iN6)
Remove the binary label (the goto statement) and use a loop instead.
Last edited on
Something along these lines:
1
2
3
4
5
6
int num=5;
cout << dec << "[0B";
for (int bi=log2(num);bi>=0;bi--) {
    cout << (num&(1<<bi)? '1' : '0');
}
cout << ']' << endl;
Why not just print the bitset?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <bitset>
#include <climits>
void print_bin(int num)
{
    // convert to binary string (could just cout << the bitset, too)
    std::string bin = std::bitset<CHAR_BIT * sizeof num>(num).to_string();
    // trim leading zeroes
    bin = num ? bin.substr(bin.find('1')) : "0";
    // print
    std::cout << num << ": [0B" << bin << ']' << '\n';
}
int main()
{
    print_bin(5);
    print_bin(42);
}

demo: http://ideone.com/WOesY
Last edited on
Topic archived. No new replies allowed.