You are here:

C++/Dotted decimal to binary conversion.

Advertisement


Question
Hi i have a problem to convert dotted decimal that is IP address into binary and convert them back  into decimal ... i don't know how to convert dotted i made a simple conversion program . can you please help me out for this.

My code for simple conversion is

#include <iostream>
using namespace std;

int main() {
   int n;  // number to convert to binary

   while (cin >> n) {
       if (n > 0) {
         cout << n << " (decimal) = ";
   
         while (n > 0) {
         cout << n%2;
         n = n/2;
         }
   
         cout << " (binary) in reverse order" << endl;
       } else {
         cout << "Please enter a number greater than zero." << endl;
       }
   }
 return 0;
}

Answer
Use a std::bitset<> to get the binary representation of a number:

#include <bitset>
#include <limits>
#include <string>

std::string to_binary( unsigned char byte )
{
   std::bitset<std::numeric_limits<unsigned char>::digits> bs(byte) ;
   return bs.to_string< char, std::char_traits<char>, std::allocator<char> >() ;
}


Use a std::istringstream to extract the four bytes of a dotted IPv4 address:

#include <iostream>
#include <string>
#include <sstream>

// ...

   std::string dotted_ipv4 = "128.74.102.46" ;

   std::istringstream stm(dotted_ipv4) ;
   unsigned char a, b, c, d ;
   char dot ;
   stm >> a >> dot >> b >> dot >> c >> dot >> d ;

// ...

Finally, get the binary representation of a,b,c,d and print it out.

// ....
   std::cout << to_binary(a) << '.' << to_binary(b) << '.'
         << to_binary(c) << '.' << to_binary(d) << '\n' ;
// ...  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.