I am trying to convert a char[12] array that contains a Mac Address into a byte[6] in order to use within the Ethernet.begin method. I have tried various methods from online, but had little success to date. The char array currently contains "A4BDC334688C" and i would like a byte array containing { A4, BD, C3, etc }.
The following is extremely close to working, with the output of the following "File Opened. A4BDC334688C A4 9D C3 34 68 6C" With BD incorecctly converting to 9D, and 8C becomming 68.
#include <SPI.h>
#include <SD.h>
#include <ArduinoJson.h>
byte ByteMacAddress[6]; // RESERVED MAC ADDRESS
StaticJsonDocument<200> doc;
int ShotCount = 0;
byte buf[40];
void setup() {
Serial.begin(9600);
//Initialise SD Card for Config
if (!SD.begin(4)) {
Serial.println("initialization failed!");
}
// open the file for reading:
File ConfigFile = SD.open("Config.txt");
if (ConfigFile) {
Serial.println("File Opened.");
} else {
Serial.println("error opening Config.txt");
}
//Deserialize Json Config in File
delay(5);
DeserializationError error = deserializeJson(doc, ConfigFile);
ConfigFile.close();
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
char* SDMacAddress = doc["MacAddress"];
Serial.println(SDMacAddress);
char arr[12];
strcpy(arr, SDMacAddress);
auto getNum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; };
byte *ptr = ByteMacAddress;
for(char *idx = arr ; *idx ; ++idx, ++ptr ){
*ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
}
//Check converted byte values.
for( byte b : ByteMacAddress )
Serial.println( b, HEX );
}
void loop(){
//Maintain DHCP Lease
//Ethernet.maintain();
//GetShotCount();
delay(500);
}
strtol(buf, &targetvariable, BASE)
like it is used in the answer to this question? You could use it do convert each byte (2 characters) individually or even - via using a union - convert the whole string at once. – chrisl Oct 17 '19 at 14:53getnum
you don't consider upper case letters. Are the letters all lower case or all upper case? – chrisl Oct 17 '19 at 16:01