For example, how a MAC address like "B4:21:8A:F0:3A:AD" can be converted into an array of 6 bytes (mac[6] = {x, x, x, x, x, x})?
Where is this "B4:21:8A:F0:3A:AD" coming from? Is it arriving through communications, or is it stored in memory, if so, in what format - Cstring or String?
if you're starting out with a C string you could use strtok to separate out the octets and strtol to convert them to bytes.
void setup()
{
Serial.begin(115200 );
while(!Serial);
char str[] = "B4:21:8A:F0:3A:AD";
uint8_t MAC[6];
char* ptr;
MAC[0] = strtol( strtok(str,":"), &ptr, HEX );
for( uint8_t i = 1; i < 6; i++ )
{
MAC[i] = strtol( strtok( NULL,":"), &ptr, HEX );
}
Serial.print(MAC[0], HEX);
for( uint8_t i = 1; i < 6; i++)
{
Serial.print(':');
Serial.print( MAC[i], HEX);
}
}
void loop() {}
possibly
strtol knows that ':' is not part of a hex number and does not need strtok to find it and set a pointer to the location. The conversion can be done without strtok. It's necessary however to increment the starting pointer past the ':' . If you don't use strtok the original character array is preserved as well.
void setup()
{
Serial.begin(115200 );
while(!Serial);
char str[] = "B4:21:8A:F0:3A:AD";
uint8_t MAC[6];
char* ptr; //start and end pointer for strtol
MAC[0] = strtol(str, &ptr, HEX );
for( uint8_t i = 1; i < 6; i++ )
{
MAC[i] = strtol(ptr+1, &ptr, HEX );
}
Serial.print(MAC[0], HEX);
for( uint8_t i = 1; i < 6; i++)
{
Serial.print(':');
Serial.print( MAC[i], HEX);
}
//original character array is preserved
Serial.println();
Serial.print(str);
}
void loop() {}
aarg:
Where is this "B4:21:8A:F0:3A:AD" coming from? Is it arriving through communications, or is it stored in memory, if so, in what format - Cstring or String?
It's a String variable, value is copy-pasted. I don't know if this format is more/less appropriate than cstring for this purpose.
I'll try both of the above codes and I'll reply back.