-->
Page 1 of 1

Need assistance converting String to byte array

PostPosted: Wed Feb 10, 2016 1:08 pm
by marklein
I want to use the WakeOnLAN example posted at https://github.com/mikispag/arduino-Wak ... eOnLan.ino It accepts a byte array for the input like this: byte pc_mac[] = {0x00, 0x24, 0x1D, 0xCD, 0x6D, 0x24}

I've made a webserver where the user can type in the target, which gets stored as a String, like this: 00241dcd6d24

Now I'm a newbie when it comes to C so this might be an easy one for a real programmer, but I'm having a devil of a time figuring out how to turn that user typed string into the byte[] that the function can use. Can anybody throw me a bone? I appreciate it.

Re: Need assistance converting String to byte array

PostPosted: Fri Feb 12, 2016 2:52 pm
by marklein
Never let a thread die unanswered! :)

At some point I realized that I was asking the question in the wrong way. What I should have been asking myself is "How do you change an ASCII HEX value into an *actual* HEX value?" Once I started down that path I ended up with the following, which works, with a little help from Google.

Code: Select allint HexDigit(byte c)
{
   if (c >= '0' && c <= '9') {
       return c - '0';
   } else if (c >= 'a' && c <= 'f') {
       return c - 'a' + 10;
   } else if (c >= 'A' && c <= 'F') {
       return c - 'A' + 10;
   } else {
       return -1;   // getting here is bad: it means the character was invalid
   }
}

int Hexify(char y, char z)
{
   byte a = HexDigit(y);
   byte b = HexDigit(z);
   if (a<0 || b<0) {
       return -1;  // an invalid hex character was encountered
   } else {
       return (a*16) + b;
   }
}

pc_mac[0] = Hexify(myString.charAt(0), myString.charAt(1));
pc_mac[1] = Hexify(myString.charAt(2), myString.charAt(3));
pc_mac[2] = Hexify(myString.charAt(4), myString.charAt(5));
pc_mac[3] = Hexify(myString.charAt(6), myString.charAt(7));
pc_mac[4] = Hexify(myString.charAt(8), myString.charAt(9));
pc_mac[5] = Hexify(myString.charAt(10), myString.charAt(11));



I'm sure that could be prettier, but heck I've got 4M to fill up. ;)