Reputation: 741
I have a function that returns a unsigned char chMAC[6];
which is the mac address and i print it out as
printf("Mac: %x",chMAC[0]);
printf("%x",chMAC[1]);
printf("%x",chMAC[2]);
printf("%x",chMAC[3]);
printf("%x",chMAC[4]);
printf("%x\n",chMAC[5]);
And i get an output as Mac: B827E82D398E
which is the actual mac address, but now i need to get that value as a string to pass to a sql parameter and i don't know how, since i need to add :
in between. such as Mac: B8:27:E8:2D:39:8E
i bet this is easy, but i am still learning C.
Upvotes: 1
Views: 1801
Reputation: 1164
You have all the pieces there, you just need to string them into the right order. Instead of using 6 separate printf() statements, pull it into one statement with all the formatting:
printf("Mac: %02X:%02X:%02X:%02X:%02X:%02X\n",
chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
The "02" in the "%02X" formatting statements will put a leading zero if the value is <15; the capital X will make the alphabetic Hex digits into capitals (which is the usual convention when passing MAC addresses).
To send the resulting string to a buffer instead of to stdout, call sprintf (or even better, snprintf) with the same formatting string.
char mac_str[24];
snprintf(mac_str, sizeof(mac_str), "Mac: %02X:%02X:%02X:%02X:%02X:%02X\n",
chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
Upvotes: 3
Reputation: 360692
why all the separate calls?
newlength = sprintf(mac, '%x:%x:%x:%x:%x:%x\n', chMAC[1], etc....)
You can have multiple %whatever
format characters in a single printf/sprintf call...
Upvotes: 0
Reputation: 41180
You probably want all the bytes to be displayed as two characters:
%2x
but with a leading 0 instead of space:
%02x
You can string this all together in one printf
call
printf("Mac: %02X:%02X:%02X:%02X:%02X:%02X\n"
, chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
If you want the text to go to a sting buffer instead of stdout
do this:
char buffer[32];
snprintf(buffer, sizeof(buffer)
, "Mac: %02X:%02X:%02X:%02X:%02X:%02X\n"
, chMAC[0], chMAC[1], chMAC[2], chMAC[3], chMAC[4], chMAC[5]);
Upvotes: 3