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

如何从Buffer中正确提取并格式化MAC地址?

Correctly Format a MAC Address from a Buffer

To fix the leading zero issue and ensure proper hex formatting (including 0xa3 displaying correctly), use a reliable method to pad each byte to two hex characters. Here's the corrected code:

const buffer = Buffer.from([0x00, 0x04, 0xa3, 0x01, 0x02, 0x90]);
// Format each byte to two-digit hex, then join with colons
const macAddress = buffer.slice(0, 6).map(byte => 
  ('0' + byte.toString(16)).slice(-2)
).join(':');
console.log(macAddress); // Output: 00:04:a3:01:02:90

Key Fixes:

  • Leading Zero Handling: Instead of relying on padStart (which requires ES2017+/Node.js 8+), concatenate a '0' before the hex string and take the last two characters with slice(-2). This works in all Node.js versions and guarantees two digits per byte.
  • Proper Hex Representation: byte.toString(16) correctly converts bytes like 0xa3 to 'a3', which is preserved in the final output.

Alternative (Modern Node.js):

If you're using Node.js 8 or newer, padStart works correctly when applied to the string result of toString(16):

const macAddress = buffer.slice(0, 6).map(byte => 
  byte.toString(16).padStart(2, '0')
).join(':');

内容的提问来源于stack exchange,提问作者tim.roberts

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:06