赞
踩
将当前Mac转换为整数加1后重新转换为Mac,就解决了进位问题
- #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
- #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;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。