C语言实现将字符串子网掩码转换为int(24之类):
对应方法(传递一个char型数组例如netmask[16]={255.255.255.0},返回24):
int subnetMaskToInt(char subnetMask[]) {
char *token = strtok(subnetMask, ".");
int i = 0;
while (token != NULL) {
int octet = atoi(token);
while (octet > 0) {
if (octet % 2 == 1) {
i++;
}
octet /= 2;
}
token = strtok(NULL, ".");
}
return i;
}
C语言分割字符串(注意malloc):
void cut_result(char *list[],char* result){
int i=1;
list[0] = strtok(result, "\n"); //第二个参数为分割标志,这里我们选择空格作为分割标志
while (list[i-1] != NULL){
list[i] = strtok(NULL, "\n"); //再次调用strtok()函数获取下一个子字符串
i++;
if(i>5){
break;
}
}
}
C获取10位和14位时间戳:
在C语言中,可以使用time()
函数获取当前时间的时间戳,但是该时间戳是10位的:
#include <stdio.h>
#include <time.h>
int main() {
time_t timestamp = time(NULL);
printf("当前时间戳: %ld", timestamp);
return 0;
}
如果需要获取14位的时间戳,可以使用gettimeofday()
函数:
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
long long timestamp = (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
printf("当前时间戳: %lld", timestamp);
return 0;
}
C截取ip的最后一个字符并转化为uint8_t类型:
uint8_t calc_node_address_from_ip(char *ip){
const char *word;
char *t_ip;
uint8_t na;
t_ip = strdup(ip);
na = 0;
strtok(t_ip, ".");
strtok(0LL, ".");
strtok(0LL, ".");
word = strtok(0LL, ".");
if ( word )
na = atoi(word);
free(t_ip);
return na;
}