首页 > 解决方案 > 如何将字符串格式化为十六进制,然后再格式化为二进制?

问题描述

我正在尝试编写一个用户输入物理 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 - ...

我该怎么做?

标签: python-3.x

解决方案


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

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

要将值作为字符串返回,我们可以使用 format 函数:

print(format(encoded_array[0], '02x'))
>>>be
print(format(toggled_array[0], '02x'))
>>>bc

如果您需要大写字母:

print(format(toggled_array[0], '02x').upper())
>>>BC

推荐阅读