How to format a string to a hexadecimal and after that to a binary?

Viewed 93

I'm trying to code a process where the user inputs a physical MAC address and EUI64 process happens. But I don't know how I can convert a letter (first or second word character) to a hexadecimal value. For example:

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

so in this case the program must convert 'B' and 'E' into binary. Also, MAC addresses can begin with a digit, so the program should determine whether it is a digit or a letter. The standard format for a MAC address is 6 groups of two hexadecimal digits separated by hyphens. A Hexadecimal 'B' is 1011 and 'E' is 1110 in binary, and in the EUI64 process, the seventh bit should be replaced with the opposite (here its '1' and opposite is '0') Binary becomes 1011 1100 (E becomes C in decimal so its BC instead of BE) After that the program should print BC - ...

How should I do this?

1 Answers

To check if a character is a letter, you can use:

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

Which returns true if the character is a letter. (You could use .isdigit() to check for integers).

There is probably an easier way of doing this, but this should work for converting the second character (note that this works whether or not the character is a digit or a letter as long as it is a valid Hex character.):

# 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)

To check what's happening, have a look at the output:

print(encoded_array)
>>>bytearray(b'\xbe')
print(bin(encoded_array[0]))
>>>0b10111110
print(toggled_array)
>>>bytearray(b'\xbc')
print(bin(toggled_array[0]))
>>>0b10111100

To get the values back as strings, we can use the format function:

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

If you need them in upper case:

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