如何将字符串格式化为十六进制然后转换为二进制?

4

我正在尝试编写一个过程,用户可以输入物理 MAC 地址并进行 EUI64 过程。但我不知道如何将字母(第一个或第二个单词字符)转换为十六进制值。例如:

mac_ad = input('Enter Your MAC address : ') (for example : BE-F0-84-DE-2F-53) 

因此,在这种情况下,程序必须将'B'和'E'转换为二进制。另外,MAC地址可以以数字开头,所以程序应该确定它是数字还是字母。 MAC地址的标准格式是6组由连字符分隔的两个十六进制数字。十六进制的'B'是1011,'E'在二进制中是1110,在EUI64过程中,第七位应替换为相反的(这里是'1'和相反的是'0')。二进制变成了1011 1100(E在十进制中变成了C,所以它是BC而不是BE)之后,程序应该打印BC - ...

我该怎么办?

1个回答

2

要检查一个字符是否为字母,您可以使用:

mac_address = 'BE-F0-84-DE-2F-53'
print(mac_address[0].isalpha())

如果字符是字母,则返回true。(您可以使用.isdigit()来检查整数)。

也许有更简单的方法来做到这一点,但是只要字符是有效的十六进制字符(无论它是数字还是字母),此方法都可以用于转换第二个字符:

# Encode the array as a bytearray using fromhex and only taking the first two characters from the string.
encoded_array = bytearray.fromhex(mac_address[:2])
# This will be our output array. Just creating a copy so we can compare.
toggled_array = bytearray(encoded_array)
# Toggle the second byte from the right. (1 << 1 is one  byte from the right, namely 2 and ^ is the XOR command)
toggled_array[0] = encoded_array[0]^(1 << 1)

为了查看发生了什么情况,请查看输出:
print(encoded_array)
>>>bytearray(b'\xbe')
print(bin(encoded_array[0]))
>>>0b10111110
print(toggled_array)
>>>bytearray(b'\xbc')
print(bin(toggled_array[0]))
>>>0b10111100

要将值作为字符串返回,我们可以使用格式化函数:
print(format(encoded_array[0], '02x'))
>>>be
print(format(toggled_array[0], '02x'))
>>>bc

如果您需要它们全部大写:
print(format(toggled_array[0], '02x').upper())
>>>BC

1
谢谢!这对我帮助很大。 - David
很高兴能够帮助! - Andrew McDowell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接