### 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
 ``1234567891011121314151617181920`` ``````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:
 ``123456`` ``````int num=5; cout << dec << "[0B"; for (int bi=log2(num);bi>=0;bi--) { cout << (num&(1<
Why not just print the bitset?

 ``1234567891011121314151617`` ``````#include #include #include void print_bin(int num) { // convert to binary string (could just cout << the bitset, too) std::string bin = std::bitset(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.