十六进制IP到字符串的C++

十六进制IP到字符串的C++,c++,string,ip,hex,C++,String,Ip,Hex,我有十六进制格式的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 >> 2

我有十六进制格式的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 ("%s\n", buff);
return 0;
}

我得到的输出是0.0.0.0,但预期的输出是239.191.200.69,atoi只接受整数。如果调用atoi1,它将返回1。如果调用atoia,它将返回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 }

上述情况可能过于复杂。仅用于示例。

猜测您的atoi不识别0xEFBFC845U。strtoul可以使用正确的参数执行此操作,如果您删除printf%s的美国可能的副本\n,xyz;是空的。我想atoi没有这个问题。在整个stackoverflow站点中,我没有得到正确的答案。在Steve共享的链接中,没有代码或十六进制IP到字符串的转换逻辑,相反,有相反的答案。这不是一个重复的问题。