如何从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 withslice(-2). This works in all Node.js versions and guarantees two digits per byte. - Proper Hex Representation:
byte.toString(16)correctly converts bytes like0xa3to'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
相关产品推荐
相关产品推荐

