将当前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;
}
相关推荐
萧西待水17 小时前
奥赛一本通 1447 靶形数独
算法·深度优先
泯泷19 小时前
那段文字是谁删的?Yjs 14 正式版之前,一套删除归属方案的实现与边界
前端·javascript·算法
hold?fish:palm20 小时前
34 合并K个升序链表
javascript·算法·链表
Navigator_Z1 天前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
语戚1 天前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp
青山木1 天前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
是隼人1 天前
buuctf-pwn [NewStarCTF 2023 公开赛道]stack migration(64位栈迁移)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
这料鬼有毒1 天前
二刷hot100-1143.最长公共子序列
算法·leetcode·动态规划
政企项目老覃1 天前
边缘 AI 推理部署:安防零售场景下的模型裁剪与端侧落地实践
人工智能·程序人生·算法·性能优化·vllm
Logic1011 天前
C语言/数据结构贪心算法题解:买卖股票的最佳时机——一次交易最大利润(O(n)时间O(1)空间)
c语言·数据结构·贪心算法·数组·时间复杂度·算法题·股票交易