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

代码如下

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;
}
标签: none
返回文章列表 文章二维码
本页链接的二维码
打赏二维码