Skip to content

Instantly share code, notes, and snippets.

@anr2me
Forked from drizzt/mac.c
Created September 16, 2021 20:25
Show Gist options
  • Save anr2me/b1df45d22d84b21296bdc13e885a7b87 to your computer and use it in GitHub Desktop.
Save anr2me/b1df45d22d84b21296bdc13e885a7b87 to your computer and use it in GitHub Desktop.

Revisions

  1. @drizzt drizzt created this gist Mar 16, 2011.
    39 changes: 39 additions & 0 deletions mac.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    /**
    * @brief Some useful C functions to manage mac addresses
    * @file
    */

    #include <stdio.h>
    #include <inttypes.h>
    #include <limits.h>

    /** Convert hex mac address to uint64_t
    * @param[in] hwaddr hex mac address
    * @return mac address as uint64_t
    */
    uint64_t mac2int(const uint8_t hwaddr[])
    {
    int8_t i;
    uint64_t ret = 0;
    const uint8_t *p = hwaddr;

    for (i = 5; i >= 0; i--) {
    ret |= (uint64_t) *p++ << (CHAR_BIT * i);
    }

    return ret;
    }

    /** Convert uint64_t mac address to hex
    * @param[in] mac uint64_t mac address
    * @param[out] hwaddr hex mac address
    */
    void int2mac(const uint64_t mac, uint8_t *hwaddr)
    {
    int8_t i;
    uint8_t *p = hwaddr;

    for (i = 5; i >= 0; i--) {
    *p++ = mac >> (CHAR_BIT * i);
    }
    }