这个看起来不容易理解,不够直观。 所以我改进了一下,使用位运算
注:
简单修改tmp
参数即可更换十进制ip
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
int main(){
// int tmp = 167772417;
int tmp = 167772161;
int ip[4], n = 0, last = 4, count = 0;
vector<int> v;
while(tmp > 0) {
int t = tmp % 2;
tmp >>= 1;
count++;
v.push_back(t);
if(count % 8 == 0 || tmp == 0){
int ans = 0;
for(int i = 0; i < v.size(); i++){
ans += v[i] * pow(2, i);
}
ip[n++] = ans;
v.clear();
}
}
for(int i = 3; i >=0; i--){
if(--last){
cout << ip[i] << ".";
}else cout << ip[i];
}
return 0;
}
运行结果:
#include <iostream>
using namespace std;
int main(){
// int tmp = 167772417;
int tmp = 167772161, buf[4], first = 1;
buf[0] = (tmp >> 24) & 0xff;
buf[1] = (tmp >> 16) & 0xff; //最前面8位自动补充为0; 00000000 11111111;
buf[2] = (tmp >> 8) & 0xff;
buf[3] = (tmp >> 0) & 0xff;
for(int i = 0; i < 4; i++){
if(first){ cout << buf[i]; first = 0;}
else cout << '.' << buf[i];
}
return 0;
}
运行结果: