Convert IP or MAC address from string to byte array (Arduino or C) -


i convert mystring "100.200.300.400" byte array [4]. i'm "bit" confused, right or need use foreach reading single number?

string mystring = "100.200.300.400"; byte mybytearray[4]; mystring.getbytes(mybytearray,4); 

finally want print array serial. should right.

for (i=0; i<4; i++) {   serial.print(mybytearray[i]);   serial.print("."); //delimiter } 

were going wrong? got 49,48,48,0 !

if trying string "100.150.200.250" byte array { 100, 150, 200, 250 }, need extract string representation each number , convert (parse) them binary representation before storing them in byte array.

the way trying this, converting first 4 bytes string, i.e. "100.", binary representation of each character, turns out { 49, 48, 48, 0 }. can in ascii table.

also remember that, storing on byte array, support values 0 255.

as programming on small microcontroller, advise against using string class. might run trouble when programs bigger , start using lots of strings. try learn how use character arrays instead , avoid running memory issues. remember arduino has 2kb of ram!

here function can use make conversion using strtoul() function:

void parsebytes(const char* str, char sep, byte* bytes, int maxbytes, int base) {     (int = 0; < maxbytes; i++) {         bytes[i] = strtoul(str, null, base);  // convert byte         str = strchr(str, sep);               // find next separator         if (str == null || *str == '\0') {             break;                            // no more separators, exit         }         str++;                                // point next character after separator     } } 

you can call convert ip address (base 10):

const char* ipstr = "50.100.150.200"; byte ip[4]; parsebytes(ipstr, '.', ip, 4, 10); 

or convert mac address (base 16):

const char* macstr = "90-a2-af-da-14-11"; byte mac[6]; parsebytes(macstr, '-', mac, 6, 16); 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -