I have a mac address in the form of a string,
00:23:34:d2:a4:00
How can this mac address index to an array?
To give a complete picture, i take the last 3 bytes in the mac address, i.e. d2:a4:00, store them in the byte array. If the corresponding bytes of d2,a4,00 are 00010001, 00110010, 00000000, then by concatenating these binary values gives me 000100010011001000000000, which if converted into an integer gives me, lets say 1000200. So, i can access the information related to that mac address using array[1000200].
If i want to do it in reverse direction, lets say i was given 1000200 number, how can i convert it into mac address 00:23:34:d2:a4:00(Assuming first 3 bytes are same for all entries). Sorry this is such a long post. It will be great help if you provide a direction. And efficiency is very important(should take very less time of execution as required for a network application). Thanks in advance.
2 Answers 2
To convert the last 3 bytes in MAC to an integer and back:
mac = 'zz:zz:zz:d2:a4:00'
i = int(''.join(mac.split(':')[-3:]), 16) # integer
# -> 13804544
h = '%06x' % i
# -> 'd2a400'
mac = 'zz:zz:zz:%s:%s:%s' % (h[0:2], h[2:4], h[4:6])
# -> 'zz:zz:zz:d2:a4:00'
You should try a dictionary with MACs as keys first as @Lattyware mentioned.
To convert an integer to MAC represented as hexstring:
>>> h = '%012x' % 123
'00000000007b'
>>> ':'.join(h[i:i+2] for i in range(0, 12, 2))
'00:00:00:00:00:7b'
2 Comments
Simply by using the split function, and then convert to binary by exploring ?
(Something like this:)
[int(_, 16) for _ in "00:23:34:d2:a4:00".split(':')]
Comments
Explore related questions
See similar questions with these tags.
some_dict["00:23:34:d2:a4:00"]id()builtin on the mac address?