0

I would like to interpret a mac string formatted like 00:11:22:33:44:55 as 6 binary bytes i.e. 0x00, 0x11, 0x22, 0x33, 0x44, 0x55. I've attemped to accomplish this with following code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main (void)
{
char mac[16]={0};
char binmac[8]={0};
char* pEnd;
strcpy(mac,"00:11:22:33:44:55");
printf("mac %s\n", mac);

binmac[0] = strtol (mac, &pEnd, 16);
binmac[1] = strtol (pEnd+1, &pEnd, 16);
binmac[2] = strtol (pEnd+1, &pEnd, 16);
binmac[3] = strtol (pEnd+1, &pEnd, 16);
binmac[4] = strtol (pEnd+1, &pEnd, 16);
binmac[5] = strtol (pEnd+1, NULL, 16);
printf ("binmac 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",binmac[0], binmac[1], binmac[2], binmac[3], binmac[4], binmac[5]);
}

But the result I get doesn't look right:

mac 00:11:22:33:44:55
binmac 0x00 0x11 0x22 0x33 0x44 0x05

I'm wondering why the last byte doesn't get interpreted correctly. Thanks

stdcerr
  • 13,725
  • 25
  • 71
  • 128

1 Answers1

2

This can be done in a much simpler manner. It looks like a commenter already caught your bug.

Code Listing


#define MAC_LENGTH   (6)

#include <stdio.h>

int main(void) {
   const char* macStr = "00:11:22:33:44:55";
   int i;
   unsigned char mac[MAC_LENGTH];
   sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
   printf("Original String:%s\n", macStr);
   printf("Parsed String:\n");
   for (i=0; i<MAC_LENGTH; i++) {
      printf("  mac[%d] = 0x%02X\n", i, mac[i]);
   }
   return 0;
}

Sample Run


Original String:00:11:22:33:44:55
Parsed String:
  mac[0] = 0x00
  mac[1] = 0x11
  mac[2] = 0x22
  mac[3] = 0x33
  mac[4] = 0x44
  mac[5] = 0x55

References


  1. How to convert Mac string to a Byte address in C, Accessed 2014-06-25, <https://stackoverflow.com/questions/12772685/how-to-convert-mac-string-to-a-byte-address-in-c>
Community
  • 1
  • 1
Cloud
  • 18,753
  • 15
  • 79
  • 153