I'm currently working on converting each piece of an ip address to binary, and I would be glad if u can tell me why my code doesn't work. The main problem is with function ip_bin(); cause it's converting the first number correctly to binary but somehow later then it is adding the first number to the second one... same situation in 2 last answers.
#include <iostream>
#include <string>
using namespace std;
string ip, mask;
string ip_string[4];
int ip_int[4], length[4];
void enter();
void get_ip();
void ip_bin();
int main(){
enter();
get_ip();
ip_bin();
return 0;}
void enter(){
cout<<"Enter ip adress: ";
cin>>ip;
cout<<"Enter mask adress: ";
cin>>mask;
}
void get_ip(){
//splitting to sections each number between the ip dots
for(int i = 0; i<4; i++){
ip_int[i] = stoi(ip.substr(0, '.'));
cout<<ip_int[i]<<endl;
string z = to_string(ip_int[i]);
int ln = z.length();
ip.erase(0, ln+1);
}
}
void ip_bin(){
int i=0, tab[31];
for(int k = 0; k<4; k++){
while(ip_int[k]){
tab[i++] = ip_int[k]%2;
ip_int[k] = ip_int[k]/2;
}
for(int j = i-1; j>=0; j--){
ip_string[k] = ip_string[k] + to_string(tab[j]);
}
length[k] = ip_string[k].length();
if(length[k]<8){
for(int g = 0; g<8 - length[k]; g++){
ip_string[k] = '0' + ip_string[k];
}
}
cout<<ip_string[k]<<endl;
}
}
Idk if u meant that but if its not what u wanted then comment i will delete, dont rep -
#include <iostream>
#include <string>
using namespace std;
string ip, mask;
string ip_string[4];
int ip_int[4], length[4];
void dec();
void enter();
void get_ip();
void ip_bin();
int main(){
enter();
get_ip();
cout <<endl;
dec();
return 0;}
void enter(){
cout<<"Enter ip adress: ";
cin>>ip;
}
void get_ip(){
//splitting to sections each number between the ip dots
for(int i = 0; i<4; i++){
ip_int[i] = stoi(ip.substr(0, '.'));
cout<<ip_int[i]<<" ";
string z = to_string(ip_int[i]);
int ln = z.length();
ip.erase(0, ln+1);
}
}
void dec() {
int bin =0;
int i=1;
for(int s=0; s<4; s++)
{
while(ip_int[s] >0 ){
bin += (ip_int[s]%2)*i;
ip_int[s] = ip_int[s]/2;
i*=10;
}
cout <<bin<<endl;
bin = 0;
i=1;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.