How to strip "\x" from MAC address (in char*) by a reusable function?

Viewed 65

I thought that I can do that easily as I was doing similar with

uint8_t array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}

But, it turns out to be, I am not there yet.

Input structure;

char *MAC_ADDR = "\x00\x22\xC7\xFF\xFF\x27";

I want it to be converted into;

char *MAC_ADDR_NEW = "0022C7FFFF27";

Your inputs are highly appreciated.

2 Answers

I'm not quite sure what reusable function means. That said, you could do the allocation and conversion with the (non-standard) asprintf function, as follows:

#include <stdio.h>
#include <stdint.h>

int main(void){
  char *MAC_ADDR = "\x00\x22\xC7\xFF\xFF\x27";
  char *MAC_ADDR_NEW;

  asprintf (&MAC_ADDR_NEW, "%02x%02x%02x%02x%02x%02x",
     (uint8_t)MAC_ADDR[0], (uint8_t)MAC_ADDR[1], (uint8_t)MAC_ADDR[2],
     (uint8_t)MAC_ADDR[3], (uint8_t)MAC_ADDR[4], (uint8_t)MAC_ADDR[5]);
  printf("%s\n", MAC_ADDR_NEW);
  free(MAC_ADDR_NEW); /* Good software hygiene is to free what you allocate. */

  /* You could reuse the same code again here for another conversion. */
  return 0;
}

The casts to uint8_t avoid sign extension for 0xFF values to FFFFFFFF, etc. Error checking left as an exercise.

$ cc x.c && ./a.out
0022c7ffff27

For completeness based on valuable inputs from @Jonathan Leffler and @Jens, I drop my proven answer.

Here is the function I've tested and started to use;

#include <stdio.h>

const unsigned char * MAC_HEX_TO_STR(char *MAC_ADDR);

const unsigned char * MAC_HEX_TO_STR(char *MAC_ADDR){
    // If static is not used, due to local variable is destroyed out of the function will return gibberish!
    static char memory[13]; 
    static char *MAC_ADDR_NEW = memory;   
    snprintf(memory, sizeof(memory), "%.2X%.2X%.2X%.2X%.2X%.2X",  (unsigned char)MAC_ADDR[0],  (unsigned char)MAC_ADDR[1],  (unsigned char)MAC_ADDR[2],  (unsigned char)MAC_ADDR[3],  (unsigned char)MAC_ADDR[4],  (unsigned char)MAC_ADDR[5]);    
    //printf(" 1 ==>>  %s\n  ", MAC_ADDR_NEW); // Debug if you like
    //MAC_ADDR_NEW[13] = 0;  // I don't know, I tried with or without but no difference observed!
    return MAC_ADDR_NEW; 
}      
int main()
{
    char *MAC_ADDR = "\x00\x22\xC7\xFF\xFF\x27";
    const unsigned char* RETURNED_MAC = MAC_HEX_TO_STR(MAC_ADDR);
    printf(" RETURNED_MAC ==>>  %s\n  ", RETURNED_MAC );

    return 0;
}

You may reach the test from here.

Related