直入主题 看看你的需求是这样的吗
String为Arduino的String
String string = "020104C0";
变成下面这个
byte[4] bytes = {0x02,0x01,0x04,0xC0};
是的话,自己Copy。 用法在最后。
void hexCharacterStringToBytes(byte *byteArray, const char *hexString)
{
bool oddLength = strlen(hexString) & 1;
byte currentByte = 0;
byte byteIndex = 0;
for (byte charIndex = 0; charIndex < strlen(hexString); charIndex++)
{
bool oddCharIndex = charIndex & 1;
if (oddLength)
{
// If the length is odd
if (oddCharIndex)
{
// odd characters go in high nibble
currentByte = nibble(hexString[charIndex]) << 4;
}
else
{
// Even characters go into low nibble
currentByte |= nibble(hexString[charIndex]);
byteArray[byteIndex++] = currentByte;
currentByte = 0;
}
}
else
{
// If the length is even
if (!oddCharIndex)
{
// Odd characters go into the high nibble
currentByte = nibble(hexString[charIndex]) << 4;
}
else
{
// Odd characters go into low nibble
currentByte |= nibble(hexString[charIndex]);
byteArray[byteIndex++] = currentByte;
currentByte = 0;
}
}
}
}
byte nibble(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return 0; // Not a valid hexadecimal character
}
怕你不知道,展示下用法。
String data = "020104C0";
//这里长度记得除下2 使用前校验一下String的长度是否正确
byte byteArray[data.length() / 2] = {0};
hexCharacterStringToBytes(byteArray, data.c_str());
两个参数,第一个接收byte的数组,第二个要String.c_str()