算法:整数与ip地址转换

时间:2023-11-27 15:11:14

直接上代码(不要直接拷贝,中间少了一行啊):

  1. #include <string>
  2. #include <iostream>
  3. using namespace std;
  4. int shu[4]={0};
  5. int IPtoINT(string s){
  6. int i,a=0,c=0,p=0;
  7. for(i=0;i<s.length();i++)
  8. {
  9. if(s[i]!='.')
  10. {
  11. a=a*10+(s[i]-'0');
  12. }else{
  13. if(a>=0&&a<=255)
  14. {
  15. shu[p++]=a;
  16. c++;
  17. }else
  18. {//cout<<"NO"<<endl;
  19. return 0;}
  20. }
  21. }
  22. if(c!=3)
  23. {//cout<<"NO"<<endl;
  24. return 0;}
  25. else
  26. {if(a>=0&&a<=255)
  27. {
  28. shu[p++]=a;
  29. }else
  30. {//cout<<"NO"<<endl;
  31. return 0;}
  32. }
  33. //cout<<"YES"<<endl;
  34. return 1;
  35. }
  36. void INTtoIP(long s)
  37. {
  38. shu[0]=s&255;
  39. shu[1]=(s&(255*256))/256;
  40. shu[2]=(s&(255*256*256))/(256*256);
  41. shu[3]=(s&(255*256*256*256))/(256*256*256);
  42. }
  43. void main(){
  44. string ips;
  45. long ipint,stoint=0;
  46. int i;
  47. cin>>ips;
  48. cin>>ipint;
  49. if(IPtoINT(ips))
  50. {
  51. for(i=0;i<4;i++)
  52. stoint=stoint*256+shu[i];
  53. cout<<stoint<<endl;
  54. }
  55. INTtoIP(ipint);
  56. if(shu[0]<256&&shu[1]<256&&shu[2]<256&&shu[3]<256)
  57. {
  58. cout<<shu[3]<<'.'<<shu[2]<<'.'<<shu[1]<<'.'<<shu[0]<<endl;
  59. }
  60. }