C语言小工具方法笔记

本文介绍了如何用C语言实现将字符串子网掩码转换为整数,以及如何使用strtok()进行字符串分割。还展示了获取10位和14位时间戳的方法,包括time()和gettimeofday()函数的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值