将当前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;
}
相关推荐
眠りたいです2 小时前
现代C++:C++14中的新语言特性和库特性
c语言·开发语言·c++
Black蜡笔小新2 小时前
自动化AI算法训练服务器DLTM助力医学影像分析进入AI智能分析新时代
人工智能·算法·自动化
手写码匠3 小时前
深入解析大模型架构之争:全能通用模型 vs 领域专精模型
人工智能·深度学习·算法·aigc
浅念-3 小时前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
列星随旋4 小时前
线段树和树状数组的学习
学习·算法
ytttr8735 小时前
OPC UA 协议栈 C 语言实现
c语言·开发语言·mfc
song5015 小时前
Ascend C 算子开发:从入门到上手
c语言·开发语言·图像处理·人工智能·分布式·flutter·交互
小a杰.6 小时前
Ascend C编程语言进阶:高性能算子开发技巧
android·c语言·开发语言
全糖可乐气泡水6 小时前
Codex适配国产信创环境安装部署与技术适配全解析
开发语言·git·python·算法·百度