需要一些帮助将 MAC 地址转换为二进制数据以在以太网帧中使用
我一直在查看各种互联网帖子,我看到的很多代码看起来都与此类似:
def mactobinar(mac):
addr = ''
temp = mac.replace(':', '')
for i in range(0, len(temp), 2):
addr = ''.join([addr, struct.pack('B', int(temp[i: i + 2], 16)))])
return addr
有人可以解释一下这段代码是如何工作的吗?
I've been looking over various internet postings and a lot of the code I've seen looks similar to this:
def mactobinar(mac):
addr = ''
temp = mac.replace(':', '')
for i in range(0, len(temp), 2):
addr = ''.join([addr, struct.pack('B', int(temp[i: i + 2], 16)))])
return addr
Can someone explain how this code works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么人们坚持写下所有这些?
Why do people insist on writing all that?
7.3。 struct — 将字符串解释为打包的二进制数据。那将是一个很好的起点。
7.3. struct — Interpret strings as packed binary data. That'd be a good place to start.
好吧,我并不是 pythen 方面最好的,但我会尝试一下。
当 mac 地址被传递到
mactobinar
时,发生的第一件事是删除分号以形成一个没有任何分隔符的常量字符串。所以 01:23:45:67:89:ab 变成 0123456789ab
好的,在下一部分中我们循环抛出一个范围,这个范围在这里创建一个偏移范围。
因此
range(0, len(temp), 2)
返回一个数组,其范围如 range(start,max,steps);然后对于该数组中的每个值,使用 struct.pack 为该整数创建一个二进制文件,并将其连接
在一起
struct.pack('B', int(temp[i: i + 2], 16)))
文档版本
struct.pack(fmt, v1, v2, ...)
pack 将实体转换为其二进制格式。
希望这能让您对这里发生的事情有一些了解
这里有一些可以帮助您入门的项目:
http://docs.python.org/library/struct.html#format-characters
http://docs.python.org/library/struct.html#struct.pack
Ok im not really the best at pythen but ill give it a shot.
when the mac address is passed into
mactobinar
the first thing that happens is that your removing the semi colon to make a constant string without any delimiters.So 01:23:45:67:89:ab becomes 0123456789ab
Ok in the next part were looping threw a range, this range here is creating a offset range.
So
range(0, len(temp), 2)
returns an array with the ranges like range(start,max,steps);then for every value in that array were creating a binary for that integer using struct.pack and also joining it together
Your version
struct.pack('B', int(temp[i: i + 2], 16)))
Documanted version
struct.pack(fmt, v1, v2, ...)
pack converts an entity into its binary format.
hope this gives you some insight on whats going here
Here are some items to get you started:
http://docs.python.org/library/struct.html#format-characters
http://docs.python.org/library/struct.html#struct.pack