Convert Byte array [in Hex] to Char array or Strin

2019-08-01 16:02发布

This question already has an answer here:

I need to convert byte array which is in hex to String.

For example:

byte array[4] = {0xAB, 0xCD, 0xEF, 0x99};
//array[0] = 0xAB;
//array[1] = 0xCD;
//array[2] = 0xEF;
//array[3] = 0x99;

Convert above to :

char number[9]; //Should be "ABCDEF99"

I have done it vice versa. That is convert char array to byte array

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();

1条回答
一夜七次
2楼-- · 2019-08-01 16:33

You need to go trough the array and add two characters (for each nibble) to the string buffer.
At the end you add the null terminator.

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';
}

Then you use it as:

byte array[4] = {0xAB, 0xCD, 0xEF, 0x99};
char str[32] = "";
array_to_string(array, 4, str);
Serial.println(str);
查看更多
登录 后发表回答