我现在正在学习c。 我的生态系统包括Espressif ESP-32微控制器和Eclipse CDT IDE。
我试图将uint8_t[]转换为人类可读的IP v4地址字符串。 到目前为止,我想到了以下代码:
void app_main (
uint8_ t [ ] IP={ 192,168,0,99 };
DUMP_IP(IP;
}
void dump _ IP (常数uint8_ t * in ) {
//ipaddressesconsistofthreedotsterminator ' '
int size=4;
//countamountofcharsneededforspecificipaddress
for(intI=0; i4; I ) {
if(in[I]==0) {
size;
} else {
size=(int ) log10 ) in[I] ) 1;
}
}
//allocatememoryonheapforanipaddressoflength ' size '
char*IP_str=(char* ) malloc ) size * sizeof (char );
//Copyipaddresspartstochararray
int pos=0;
for(intI=0; i4; I ) {
if(in[I]==0) {
ip_str[pos]='0';
销售点;
} else {
char b[4];
itoa(in[I],b,10 );
for(intj=0; j3; j ) {
if(b[j]!='0' ) {
ip_str[pos]=b[j];
销售点;
}
}
}
//add dot between IP地址部件
if(I3 ) {
ip_str[pos]='.';
销售点;
}
}
//add terminator at end of string
ip_str[pos]=' ';
//打印到UART接口
URT_send(IP_str );
//release allocated heap memory
free(IP_str );
}
使用不同的IP阵列进行测试时,得到了以下结果:
uint8_ t [ ] IP={ 192,168,0,99 };='192.168.0.99'=OK确定
uint8_ t [ ] IP={ 192,168,1,99 };=' 192.168.1 '=故障
uint8_ t [ ] IP={ 192,168,10,99 };=' 192.168.1 '=故障
uint8_ t [ ] IP={ 10,10,10 };='1'=故障
//etc. etc. etc。
我到底做了什么? 有更优雅的方法来实现这个目标吗?