wangx1ng wangx1ng - 4 months ago 27
C Question

Converting char[][] to char[] in C++

Now I have a char array with the mac address stored in:

char mac_addr[6];


And I
sprintf
it into another char array:

char cmdstr[64];
sprintf(cmdstr, "MAC: %2x:%2x:%2x:%2x:%2x:%2x;",
mac_addr[0], mac_addr[1], mac_addr[2],
mac_addr[3], mac_addr[4], mac_addr[5]);


When I print
cmdstr
, it looks like this:

MAC: 08:10:76:10:26:21;


Then I send the
cmdstr
to a remote server, there is a parse function to parse this char array. After the
cmdstr
is parsed, the six parts separated by a
:
are stored in a multi char array:

char mac[6][10];


With:

char mac[0] = "08"
char mac[1] = "10"
char mac[2] = "76"
char mac[3] = "10"
char mac[4] = "26"
char mac[5] = "21"


Now, on the server side, how can I re-convert each part of the mac address to char and make it possible that the whole mac address can be stored in a char array like this?

char my_mac[6];


With:

my_mac[0] = '08'
my_mac[1] = '10'
my_mac[2] = '76'
my_mac[3] = '10'
my_mac[4] = '26'
my_mac[5] = '21'


Many thanks!

Edit:



Sorry I think I described something wrongly, the text
'08'
itself should not stored in
my_mac[0]
. Actually when I gdb the program, I found that:

(gdb) p mac_addr[0]
$15 = 8 '\b'
(gdb) p mac_addr[1]
$16 = 16 '\020'
(gdb) p mac_addr[2]
$17 = 118 'v'
(gdb) p mac_addr[3]
$18 = 16 '\020'
(gdb) p mac_addr[4]
$19 = 38 '&'
(gdb) p mac_addr[5]
$20 = 33 '!'


I think I should convert the
mac[6][10]
to a char array just like above.

Answer

You can use strtol function in stdlib.h

char *dummy;
for (int i = 0; i < 6; i++) {
    my_mac[i] = strtol(mac[i], &dummy, 16);
}