/*题目4:(简答题:10.0分) 实现函数将点分十进制表示的字符串转换为 unsigned int 整型数值 unsigned int my_ResDotDec(const char *strip); 参数说明:strip 点分十进制表示的字符串; 示例: strip =“128.11.3.31” ; 返回值: 2148205343; strip =“128.399.2.12” ; 返回值为 UINT_MAX
#include <iostream> #include <ctype.h> #include <limits.h> #include <stack> using namespace std; //处理单个atoi int my_atoi_single(const char p) { return p - '0'; } //atoi的子函数,将进制,字符,符号传递进来 unsigned int my_atoi_Son(const char *p,int system) { stack<char> sta; unsigned int sum = 0; unsigned int tmp = 0; while(isdigit(*p)) { sta.push(*p); p++; } int n = sta.size(); for(int i = 0; i < n;++i) { tmp = my_atoi_single(sta.top()); sta.pop(); for(int j = 0;j < i;++j) { tmp = tmp * system; } sum += tmp; } return sum; } unsigned int my_atoi(const char *str) { unsigned int integer = 0; int system = 10; const char * p = str; if(!isdigit(*p)) { throw exception("输入的字符串,无法进行atoi!"); } integer = my_atoi_Son(p,system); return integer; } void DDN_to_UIN_Son(char *str,char *des,int i,int n) { char * p = des; char * q = str; p = p + (i * 8) + 8 - n; while(n--) { *p++ = *q++; } } //二进制字符串转成无符号整型 unsigned int BINChar_to_UIN(const char *buffers) { stack<char> sta; unsigned int sum = 0; unsigned int tmp = 0; const char * p = buffers; int i ,j; for(i = 0;i < 32;++i) { sta.push(*p); ++p; } for(i = 0; i < 32;++i) { if(sta.top() == '0') { tmp = 0; } else { tmp = 1; } sta.pop(); for(j = 0;j < i;++j) { tmp = tmp * 2; } sum += tmp; } return sum; } //10进制数转2进制,并保存在bool类型数组中 void DEC_to_BIN(unsigned int value, bool *buffer,int i) { bool * p = buffer; bool itmp = 0; int n = 0; stack<bool> sta; while(value) { itmp = value%2; value = value/2; sta.push(itmp); } n = sta.size(); p = p + (i+1) * 8 - n; while(!sta.empty()) { *p = sta.top(); sta.pop(); ++p; } } //二进制数转成无符号整型 unsigned int BIN_to_UIN(bool *p) { stack<bool> sta; unsigned int sum = 0; unsigned int tmp = 0; int i ,j; for(i = 0;i < 32;++i) { sta.push(*p); ++p; } for(i = 0; i < 32;++i) { tmp = sta.top(); sta.pop(); for(j = 0;j < i;++j) { tmp = tmp * 2; } sum += tmp; } return sum; } //点分十进制转为unsigned int 整型数值记法 unsigned int DDN_to_UIN(const char *IP_address) { const char *p = IP_address; bool buffers[32] = {0} ; char buff[3] = {0}; unsigned int s = 0; long long tmp = 0; for(int i = 0;i < 4;++i) { memset(buff,'*',3); for(int j = 0;j < 3;++j) { buff[j] = *p; ++p; if(*p == '.' || *p == '\0') { ++p; break; } } tmp = my_atoi(buff); if(tmp > 255) { return UINT_MAX; } DEC_to_BIN(tmp,buffers,i); } s = BIN_to_UIN(buffers); return s; } int main() { printf("%u\n", DDN_to_UIN("128.399.2.12")); printf("%u\n",UINT_MAX); }