c++ - How to convert a char array to a byte array on Arduino? -
im working on project , i'm stuck problem how can convert char array byte array?.
for example: need convert char[9] "fff2bdf1" byte array byte[4] 0xff,0xf2,0xbd,0xf1.
thanks in advance.
here little arduino sketch illustrating 1 way this:
void setup() { serial.begin(9600); char arr[] = "abcdef98"; byte out[4]; auto getnum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; }; byte *ptr = out; for(char *idx = arr ; *idx ; ++idx, ++ptr ){ *ptr = (getnum( *idx++ ) << 4) + getnum( *idx ); } //check converted byte values. for( byte b : out ) serial.println( b, hex ); } void loop() { }
the loop keep converting until hits null character. code used in getnum
only deals lower case values. if need parse uppercase values easy change. if need parse both little more code, i'll leave if needed (let me know if cannot work out , need it).
this output serial monitor 4 byte values contained in out
after conversion.
ab
cd
ef
98
edit: how use different length inputs.
the loop not care how data there is, long there number of inputs (two ascii chars each byte of output) plus single terminating null. stops converting when hits input strings terminating null.
so longer conversion in sketch above, need change length of output (to accommodate longer number). i.e:
char arr[] = "abcdef9876543210"; byte out[8];
the 4
inside loop doesn't change. shifting first number position.
for first 2 inputs ("ab"
) code first converts 'a' number 10
, or hexidecimal a
. shifts left 4 bits, resides in upper 4 bits of byte: 0a
a0
. second value b
added number giving ab
.