Petr Bečka
Petr Bečka

Reputation: 794

C - converting char* to unsigned char array

I'm trying hard to convert char *macAddress into unsigned char mac[6] but without success so far. My input string looks like "00:10:6f:16:01:b3" and I want to devide it into mac[0] = 0x00, mac[1] = 0x10, etc..

I've tried to use memcpy like:

memcpy(&mac, (unsigned char)macAddress, sizeof mac);  

or same another ways like mac = (unsigned char *)macAddress and so on but nothing worked for me well.
Is there any correct way how to convert it without any precision loss?

Upvotes: 0

Views: 592

Answers (1)

Ludwig Schulze
Ludwig Schulze

Reputation: 2325

You want to convert hexadecimal digits (i.e. the string "00") of the mac address to byte values (i.e. the value 0). The memcpy instead copies the value of the string digits (i.e. '0' is 48 or 0x30).

You can use sscanf for the correct conversion.

At least on Linux, you can also use the function ether_aton. See the man page.

Upvotes: 2

Related Questions