gaqwarrior.blogg.se

Convert mac address 48 bit python
Convert mac address 48 bit python






Speed isn't a huge concern, but I'm curious if there's a cleaner way that I'm missing.ĭef random_mac(unicast: bool = True, universal: bool = True) -> str: Attaching the first octet to the rest is suboptimal as well.Is treating a boolean value as a number during bitwise operation idiomatic? Is it clear as I have it now?.The numbers kind of sit on a border of self-explanatory and magic, so I decided to name them to be safe. The number constants are bugging me too.I tried explicitly setting the bits, but the code to decide between |, and & and ~ got messier than what I have now, so I went with this way. Is there a better approach? It feels hacky generating it as two pieces then adding them together.It's not a lot of code, but I'd like a few things reviewed: It works, but it's ugly and looks suboptimal. The LSB of the first octet indicates uni/multicast, and the second LSB of the octet indicates universal/local, so these bits can't be random.Īfter playing around with a few failed ideas (generating all random bits, then "fixing" the two bits later), I finally decided to generate a random number between 0 and 63 inclusive, left shift it twice, than add the two bits on after. This caused me headaches though because I'm still not great at dealing with bits. I decided to allow the user to pick if it's unicast/multicast and universally/locally administered even though I'll only need unicast/universal. > random_mac(unicast=True, universal=False) > random_mac(unicast=False, universal=True) I need the ability to generate random MAC addresses, so I wrote up a little function that does that: > random_mac() UUID ( '' ) > # convert a UUID to a string of hex digits in standard form > str ( x ) '00010203-0405-0607-0809-0a0b0c0d0e0f' > # get the raw 16 bytes of the UUID > x.








Convert mac address 48 bit python