使用C++将十六进制IP转换为字符串

Hexadecimal IP to String using C++

本文关键字:转换 字符串 IP 十六进制 C++ 使用      更新时间:2023-10-16

我有十六进制格式的IP4地址,需要转换为字符串。你能告诉我以下代码中需要更改什么才能得到正确的答案吗。非常感谢您的支持。

int main (void) {
char buff[16];
string  IpAddressOct = "EFBFC845";
string xyz="0x"+IpAddressOct+"U";
unsigned int iStart=atoi(xyz.c_str());
sprintf (buff, "%d.%d.%d.%d", iStart >> 24, (iStart >> 16) & 0xff,(iStart >> 8) & 0xff, iStart & 0xff);
printf ("%sn", buff);
return 0;
}

我得到的输出是0.0.0.0,但预期输出是239.191.200.69

atoi()只接受整数。如果你调用atoi("1"),它将返回1。如果您调用atoi("a"),它将返回0。

您应该做的是在十六进制值之间创建一个映射,并每两个字符进行一次计算。以下是一个示例:

  1 #include <map>
  2 #include <iostream>
  3 #include <cstring>
  4 #include <string>
  5 #include <vector>
  6
  7 using namespace std;
  8
  9 static std::map<unsigned char, int> hexmap;
 10
 11 void init() {
 12     hexmap['0'] = 0;
 13     hexmap['1'] = 1;
 14     hexmap['2'] = 2;
 15     hexmap['3'] = 3;
 16     hexmap['4'] = 4;
 17     hexmap['5'] = 5;
 18     hexmap['6'] = 6;
 19     hexmap['7'] = 7;
 20     hexmap['8'] = 8;
 21     hexmap['9'] = 9;
 22     hexmap['a'] = 10;
 23     hexmap['A'] = 10;
 24     hexmap['b'] = 11;
 25     hexmap['B'] = 11;
 26     hexmap['c'] = 12;
 27     hexmap['C'] = 12;
 28     hexmap['d'] = 13;
 29     hexmap['D'] = 13;
 30     hexmap['e'] = 14;
 31     hexmap['E'] = 14;
 32     hexmap['f'] = 15;
 33     hexmap['F'] = 15;
 34 }
 35
 36 vector<int> parseIp(string income) {
 37     vector<int> ret;
 38     if (income.size() > 8)
 39         // if incoming string out of range
 40         return ret;
 41     int part = 0;
 42     char buf[4];
 43     for (int i = 0; i < income.size(); ++i) {
 44         part += hexmap[income[i]];
 45         cout << income[i] << " " << hexmap[income[i]] << " " << part << endl;
 46         if ((i % 2) == 1) {
 47             ret.push_back(part);
 48             part = 0;
 49         } else {
 50             part *= 16;
 51         }
 52     }
 53
 54     return ret;
 55 }
 56
 57 int main(void) {
 58     init();
 59     string ipAddressOct = "EFBFC845";
 60     vector<int> ip = parseIp(ipAddressOct);
 61     cout << ip[0] << "." << ip[1] << "." << ip[2] << "." << ip[3] << endl;
 62 }

以上内容可能过于复杂。它仅用于举例说明。