无符号整型转点分十进制

    技术2023-03-27  78

    /*题目3:(简答题:10.0分) 实现函数将 unsigned int 整型数值转为点分十进制记法表示: 点分十进制(Dotted Decimal Notation)全称为点分(点式)十进制表示法, 是IPv4的IP地址标识方法。 IPv4中用四个字节表示一个IP地址,每个字节按照十进制表示为0~255。 点分十进制就是用4个从0~255的数字,来表示一个IP地址。 char * my_DotDec(unsigned int ip,char *buffer); 参数说明: value:欲转换的数数值。 buffer:目标字符串的地址。 示例: ip = 2148205343; buffer = “128.11.3.31”;

    注意,无符号整形变量命名,不然一天就过去了

    #include <iostream> #include <ctype.h> #include <stack> using namespace std; char my_itoa_single(int p,int radix) { if(radix == 16 && p >= 10) { return p + 'W'; } else { return p + '0'; } } void my_itoa(unsigned value, char *buffer, int radix) { char * p = buffer; unsigned itmp = 0; char ctmp; stack<char> sta; if(radix != 10) { *p = '0'; ++p; if(radix == 16) { *p = 'X'; ++p; } } while(value) { itmp = value%radix; value = value/radix; ctmp = my_itoa_single(itmp,radix); sta.push(ctmp); } while(!sta.empty()) { *p = sta.top(); sta.pop(); ++p; } } //10进制数转2进制,并保存在bool类型数组中 void DEC_to_BIN(unsigned int value, bool *buffer) { bool * p = buffer; bool itmp = 0; stack<bool> sta; while(value) { itmp = value%2; value = value/2; sta.push(itmp); } 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 < 8;++i) { sta.push(*p); ++p; } for(i = 0; i < 8;++i) { tmp = sta.top(); sta.pop(); for(j = 0;j < i;++j) { tmp = tmp * 2; } sum += tmp; } return sum; } //unsigned int 整型数值转为点分十进制记法 void UIN_to_DDN(unsigned int value, char *IP_address) { bool buffer[32] = {0}; DEC_to_BIN(2148205343, buffer); bool *p = buffer; char *q = IP_address; unsigned int tmp = 0; for(int i = 0;i < 4;++i) { tmp = BIN_to_UIN(p); my_itoa(tmp,q,10); while(*q != '\0') { ++q; } *q = '.'; ++q; p = p + 8; } --q; *q = '\0'; } int main() { bool buffer[32] = {0}; char IP_address[16] = {0}; DEC_to_BIN(2148205343, buffer); for(int i = 0;i < 32;i++) { printf("%d",buffer[i]); } printf("\n"); printf("%d\n",BIN_to_UIN(buffer)); UIN_to_DDN(2148205343,IP_address); printf("%s\n",IP_address); return 0; }
    Processed: 0.022, SQL: 10