You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言如何将MAC地址转换为对应十六进制值的字节数组

错误原因

你报错的核心原因是a是[]string类型,而append到[]byte里的元素必须是byte类型,两者类型不匹配。你拼接的0x前缀的内容本质还是文本字符串,不是实际的十六进制数值,无法直接作为字节使用。


推荐实现(调用标准库,无需重复造轮子)

Go标准库net包已经内置了MAC地址解析方法net.ParseMAC,直接调用即可得到对应字节数组,支持冒号分隔、横杠分隔等多种常见MAC格式,可靠性远高于手动实现:

package main

import (
	"fmt"
	"net"
)

func main() {
	macStr := "00:19:10:08:FE:08"
	// 解析MAC地址为字节数组
	macBytes, err := net.ParseMAC(macStr)
	if err != nil {
		// 此处替换为你自己的非法格式处理逻辑
		panic("MAC地址格式错误:" + err.Error())
	}
	fmt.Printf("%#v\n", macBytes) // 输出:[]byte{0x0, 0x19, 0x10, 0x8, 0xfe, 0x8}

	// 追加到已有字节数组
	myByte := []byte{0x15, 0x1a}
	myByte = append(myByte, macBytes...)
	fmt.Printf("%#v\n", myByte) // 输出:[]byte{0x15, 0x1a, 0x0, 0x19, 0x10, 0x8, 0xfe, 0x8}
}

手动实现版本(仅用于了解转换原理)

如果需要自己实现转换逻辑,可以把分割后的每个十六进制字符串转成数值再转byte:

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	macStr := "00:19:10:08:FE:08"
	parts := strings.Split(macStr, ":")
	macBytes := make([]byte, len(parts))
	for i, part := range parts {
		val, err := strconv.ParseUint(part, 16, 8)
		if err != nil {
			panic("分段格式错误:" + err.Error())
		}
		macBytes[i] = byte(val)
	}
	fmt.Printf("%#v\n", macBytes)
}

内容的提问来源于stack exchange,提问作者offhuman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 14:54:04