简体   繁体   中英

Converting a string of mac address into hex in C

I want to convert a string of mac address into hex format.

  • Input:
char remote_device_mac[] = "00a05056a810";
  • Expected output:
uint8_t base_mac_addr[6] = {0x00,0xa0,0x50,0x56,0xa8,0x10};

My code:-

char dummy[2] = {0};
int j = 0;
uint8_t num = 0;
     for(int k=0;k<6;k++)
     {
        for(int i=0;i<2;i++)
            dummy[i] = remote_device_mac[i+j];

        num = (int)strtol(dummy, NULL, 8);
        j=j+2;
        sprintf(base_mac_addr[k], "%x", num);

        num = 0; 
        memset(dummy,0,2);
     }
char dummy[2] = {0};

size of dummy has at least 3 bytes (2 for value in hexa, 1 for \0 ). So you can declare as:

char dummy[3] = "00";

Use base = 16 instead of 10, because you want to convert to hexadecimal.

num = strtol(dummy, &ptr, 16);

sprintf is not necessary (use it if you want to copy number into a string).

// assign each base_mac_addr to num.
base_mac_addr[k] = num;

Finally, the code as below:

     for(int k=0;k<6;k++)
     {
        for(int i=0;i<2;i++)
            dummy[i] = remote_device_mac[i+j];
        num = strtol(dummy, &ptr, 16);
        j=j+2;
        printf("0x%2x\n", num);
        base_mac_addr[k] = num;
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM