我需要将十六进制的字节数组转换为String。
例如:
byte array[4] = {0xAB, 0xCD, 0xEF, 0x99};
//array[0] = 0xAB;
//array[1] = 0xCD;
//array[2] = 0xEF;
//array[3] = 0x99;
将上述内容转换为:
char number[9]; //Should be "ABCDEF99"
我已经完成了反之亦然。这是将char数组转换为字节数组
char CardNumber[9] = "ABCDEF99";
byte j;
auto getNum = [](char c)
{
return c > '9' ? c - 'a' + 10 : c - '0';
};
char arr[10];
char i;
byte *ptr = out;
for (i = 0; i < 8; i++)
{
arr[i] = CardNumber[i];
}
for (char *index = arr ; *index ; ++index, ++ptr )
{
*ptr = (getNum( *index++ ) << 4) + getNum(*index);
}
//Check converted byte values.
Serial.print("Card Number in Bytes :");
for (j = 0; j < 4; j++)
{
Serial.print(out[j], HEX );
}
Serial.println();
答案 0 :(得分:7)
你需要通过数组并将两个字符(对于每个半字节)添加到字符串缓冲区 最后添加null终止符。
void array_to_string(byte array[], unsigned int len, char buffer[])
{
for (unsigned int i = 0; i < len; i++)
{
byte nib1 = (array[i] >> 4) & 0x0F;
byte nib2 = (array[i] >> 0) & 0x0F;
buffer[i*2+0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA;
buffer[i*2+1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA;
}
buffer[len*2] = '\0';
}
然后你用它作为:
byte array[4] = {0xAB, 0xCD, 0xEF, 0x99};
char str[32] = "";
array_to_string(array, 4, str);
Serial.println(str);