将当前mac地址转换为整数加n后重新转换为Mac地址

将当前Mac转换为整数加1后重新转换为Mac,就解决了进位问题

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 将 MAC 地址转换为整数
unsigned long long mac_to_int(char *mac) {
    char mac_str[18];
    strcpy(mac_str, mac);
    char *ptr = strtok(mac_str, ":");
    unsigned long long mac_int = 0;
    while (ptr != NULL) {
        mac_int = (mac_int << 8) + strtoul(ptr, NULL, 16);
        ptr = strtok(NULL, ":");
    }
    return mac_int;
}

// 将整数转换为 MAC 地址
void int_to_mac(unsigned long long mac_int, char *mac) {
    sprintf(mac, "%02llX:%02llX:%02llX:%02llX:%02llX:%02llX",
            (mac_int >> 40) & 0xFF, (mac_int >> 32) & 0xFF, (mac_int >> 24) & 0xFF,
            (mac_int >> 16) & 0xFF, (mac_int >> 8) & 0xFF, mac_int & 0xFF);
}

int main() {
    char current_mac[] = "00:11:22:33:44:55";
    unsigned long long mac_int = mac_to_int(current_mac);
    mac_int += 1;
    
    char new_mac[18];
    int_to_mac(mac_int, new_mac);

    printf("当前 MAC 地址:%s\\n", current_mac);
    printf("加1后的 MAC 地址:%s\\n", new_mac);

    return 0;
}

情形2

cpp 复制代码
#include <stdio.h>
#include <stdint.h>

typedef uint8_t u8;

// 将 MAC 地址转换为整数
uint64_t mac_to_int(u8 source_mac[6]) {
    uint64_t mac_int = 0;
    for (int i = 0; i < 6; i++) {
        mac_int = (mac_int << 8) + source_mac[i];
    }
    return mac_int;
}

// 将整数转换为 MAC 地址
void int_to_mac(uint64_t mac_int, u8 dest_mac[6]) {
    for (int i = 5; i >= 0; i--) {
        dest_mac[i] = mac_int & 0xFF;
        mac_int >>= 8;
    }
}

int main() {
    u8 source_mac[6] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55};
    uint64_t mac_int = mac_to_int(source_mac);
    mac_int += 1;
    
    u8 new_mac[6];
    int_to_mac(mac_int, new_mac);

    printf("当前 MAC 地址:");
    for (int i = 0; i < 6; i++) {
        printf("%02X:", source_mac[i]);
    }
    printf("\\n");

    printf("加1后的 MAC 地址:");
    for (int i = 0; i < 6; i++) {
        printf("%02X:", new_mac[i]);
    }
    printf("\\n");

    return 0;
}
相关推荐
weixin_4461224620 分钟前
LinkedList剖析
算法
百年孤独_1 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程2 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生2 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生2 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧2 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao2 小时前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展
ゞ 正在缓冲99%…2 小时前
leetcode67.二进制求和
算法·leetcode·位运算
YuTaoShao2 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II——排除法
java·算法·leetcode