MAC地址:pad missing left Zeros [英] MAC address:pad missing left Zeros
问题描述
例如,我有一个MAC地址的值为0:22:3f:a:5d:16,我如何将其转换为人类可读的格式,如00:22:3f:0a:5d :16?
我的mac地址缺少前导零,因为我使用
For example i have a MAC address that has a value of "0:22:3f:a:5d:16", how do i convert this to a human readable format like "00:22:3f:0a:5d:16"? My mac Address has missing leading zeros because i use
string asd = ether_ntoa ((struct ether_addr *)p->add2);//p->add2 is a unsigned char[6]
ether_nota removed前导零,我不知道是否有其他方法来存储一个正确的MAC地址作为字符串。
ether_nota removes the leading zeros,i don't know if there are other ways to store a proper MAC addresses as a string.
推荐答案
实现导致它打印没有零填充只是一个 printf
他们使用%x
而不是
%02x
。 struct ether_addr
格式为
The implementation that causes it to print without zero padding is just a printf
where they use %x
instead of %02x
. The struct ether_addr
format is documented in the man page, and therefore its internals are not private.
The structure ether_addr is defined in <net/ethernet.h> as:
struct ether_addr {
uint8_t ether_addr_octet[6];
}
所以说,我会实现自己的版本。 rz
表示可重入和零填充。
So that being said, I'd implement my own version. rz
means reentrant and zero padded here.
char *ether_ntoa_rz(const struct ether_addr *addr, char *buf)
{
sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
addr->ether_addr_octet[0], addr->ether_addr_octet[1],
addr->ether_addr_octet[2], addr->ether_addr_octet[3],
addr->ether_addr_octet[4], addr->ether_addr_octet[5]);
return buf;
}
非可重入版本只有一个静态缓冲区并调用可重入的。
The non-reentrant version would just have a static buffer and call the reentrant one.
char *ether_ntoa_z(const struct ether_addr *addr)
{
static char buf[18]; /* 12 digits + 5 colons + null terminator */
return ether_ntoa_rz(addr, buf);
}
如果要查看glibc中函数的实现,如果您搜索,请查找。
If you want to look at the implementation of the function in glibc, you can find it if you search.
这篇关于MAC地址:pad missing left Zeros的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!