How do I convert a String which has hex values to a byte array that has those hex values? I am using Arduino by the way.
This:
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";
Needs to be converted to this:
char test[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
I used the following procedure. It does convert it, however, each hex value is saved as a character as opposed to hex value:
unsigned int str_len = s.length()+1;
char charArray[str_len];
s.toCharArray(charArray, str_len);
I am assuming you need an array of hex values ie array of integers from the String s
. Thogh from char test[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
, it seems you want a char array. If you add the code below after your code you will get an integer array named hexn
which will contain your hex values.
int i,hexn[20],k=0,j;
char tmp[8];
for (i=0;charArray[i]!='\0' ;i++){
if(charArray[i]=='x' && charArray[i-1]=='0'){
j=0;
while(charArray[i]!=','){
tmp[j++]=charArray[++i];
if (charArray[i]=='\0')
break;
}
sscanf(tmp,"%x",&hexn[k++]);
}
}
Now if you really need char test[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
, I suppose you are not getting the opening and closing braces, ie {
and }
. in that case you can use the concatenation operator. You can to do something like this before your code,
String s2 = String('{') + s + String('}');
Hope it will help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.