0%

C++ 实现的ip字符串与数字的转换

C++ 实现的ip字符串与数字的转换算法

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class ip_util{
public:
char * get_ip_address( int ip_in_number);
private:
char * transform_integer_to_string(int orign_number);
};

char * ip_util::transform_integer_to_string(int orign_number){
char * c = new char[ 64 + 1 ];
char * pointer1 = c ;
char * temp = new char[64+1];
char * temp_pointer = temp;
while ( orign_number > 0 ) {
*(pointer1 ++) = ( orign_number%10) + '0';
orign_number /= 10;
}
pointer1 --;
while (pointer1 >= c) {
*(temp_pointer++ ) = *pointer1;
pointer1 --;
}
*temp_pointer = '\0';
free(c);
return temp;
}

char * ip_util::get_ip_address( int ip_in_number)
{
int data[4];
char * c = new char[16];
char * pointer = c;
for(int i = 0 ; i < 4 ; i ++ ){
data[i] = ( ip_in_number & 0xff );
ip_in_number >>= 8;
}
for (int i = 3; i >= 0 ; i --) {
char * target_str = transform_integer_to_string(data[i]);
if( target_str != NULL ){
char * target_temp = target_str;
while ( * target_temp != '\0' ) {
*(pointer++) = *(target_temp++);
}
free(target_str);
}
if( i > 0 ){
*(pointer++) = '.';
}
}
return c;
}



int main(int argc, const char * argv[]) {
ip_util ip;
std::cout << ip.get_ip_address(0x0f121320) << std::endl;
return 0;
}