如何将字节数组的字符串转换为字节数组
How to convert the string of a byte array to a byte array
这可能看起来有点愚蠢,但我正在我的 RFID 卡上写入数据,并且我以这些形式写入:
{0x31,0x32,0x33,0x39}
我现在把它放在一个字符串中
"0x31,0x32,0x33,0x39"
有什么方法可以从字符串传递到字节数组吗?
提前致谢!
这是我到目前为止的代码,但我真的不知道如何让它工作抱歉,我是新手,但 Steve Summit 我需要按特定顺序使用所有代码吗?
String str = "0x31,0x32,0x33,0x39";
byte Myarray[18];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
int i = 0;
void loop() {
for (i; i<str.length();++i) {
Myarray[i] = strtol(str, 0, 16);
}
Serial.println(Myarray);
}
您可以使用 C 函数 strtok to tokenize the string. You can use strtol 将字符串转换为数字。
char data[] = "0x31,0x32,0x33,0x39";
byte arr[4];
int length = 0;
const char* delim = ",";
char* tok = strtok(data, delim);
while (tok && length < sizeof(arr)) {
arr[length++] = strtol(tok, NULL, 16);
tok = strtok(NULL, delim);
}
for (int i = 0; i < length; i++) {
Serial.print(arr[i], HEX);
Serial.print(' ');
}
注意:strtok 会发生变化 data
。它会将分隔符 ,
替换为字符串终止符。
0x31 = 49 所以
我可以这样写:
{49,50,51,57}
哪个更容易创建。
这可能看起来有点愚蠢,但我正在我的 RFID 卡上写入数据,并且我以这些形式写入:
{0x31,0x32,0x33,0x39}
我现在把它放在一个字符串中
"0x31,0x32,0x33,0x39"
有什么方法可以从字符串传递到字节数组吗? 提前致谢!
这是我到目前为止的代码,但我真的不知道如何让它工作抱歉,我是新手,但 Steve Summit 我需要按特定顺序使用所有代码吗?
String str = "0x31,0x32,0x33,0x39";
byte Myarray[18];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
int i = 0;
void loop() {
for (i; i<str.length();++i) {
Myarray[i] = strtol(str, 0, 16);
}
Serial.println(Myarray);
}
您可以使用 C 函数 strtok to tokenize the string. You can use strtol 将字符串转换为数字。
char data[] = "0x31,0x32,0x33,0x39";
byte arr[4];
int length = 0;
const char* delim = ",";
char* tok = strtok(data, delim);
while (tok && length < sizeof(arr)) {
arr[length++] = strtol(tok, NULL, 16);
tok = strtok(NULL, delim);
}
for (int i = 0; i < length; i++) {
Serial.print(arr[i], HEX);
Serial.print(' ');
}
注意:strtok 会发生变化 data
。它会将分隔符 ,
替换为字符串终止符。
0x31 = 49 所以 我可以这样写:
{49,50,51,57}
哪个更容易创建。