1

I am using Arduino. I have the following code which converts binary data to its ASCII equivalent. It uses the String object.

static uint16_t index = 0;
static char buffer[1600]; //contains binary data 0x11, 0x22, 0x1, 0xa ...

String msg;
index = strlen(buffer);
for (i=0; i < index; i++)
{
    //Produce a zero in front for single digits. Examples, 0x5 transforms into 05, 0xa transforms into 0a
    if (buffer[i] <= 0x0F)
    {
        msg += "0";
    }

    msg += String(buffer[i], HEX); //msg contains the ASCII equivalent of buffer    
}

How can the code be modified such that the String object is not used but the same objective is accomplished?

2
  • 2
    static uint16_t index = 0; and for (i=0; i < index; i++) are you sure that's correct? Commented Aug 16, 2016 at 11:03
  • THanks for catching the error. index should be length of the buffer. Commented Aug 16, 2016 at 11:06

3 Answers 3

1

Simply convert each digits.

static char digits[] = "0123456789abcdef"; // characters used to represent digits

static uint16_t index = 0;
static char buffer[1600]; //contains binary data 0x11, 0x22, 0x1, 0xa ...

static char msg[3201]; // 2 digits for each bytes and 1 terminating null-character

for (i=0; i < index; i++)
{
    //Produce a zero in front for single digits. Examples, 0x5 transforms into 05, 0xa transforms into 0a
    msg[i * 2] = digits[((unsigned char)buffer[i] >> 4) & 0xf];

    msg[i * 2 + 1] = digits[(unsigned char)buffer[i] & 0xf]; //msg contains the ASCII equivalent of buffer
}

msg[index * 2] = '\0'; // terminate the string

Arduino may not be capable to store 4KB data (SRAM on ATmega328P is only 2KB), so reduce the buffer size if they are too much.

Sign up to request clarification or add additional context in comments.

Comments

1

Pure C solultion:

#include <stdio.h>
#include <stdlib.h>

int main()
{
const unsigned char bytes[] = {0x04, 0x55, 0x56, 0xce , 0xdf };
int i;
int sz = sizeof(bytes);
char *result = (char*)malloc(sz*4+1);
char *current = result;

for (i = 0; i < sz; i++)
{
    sprintf(current,"%02x",bytes[i]);
    current += 2;
}
printf("Result : %s\n",result);
free(result);
}

result:

045556cedf

You can also change "%02x" format by "%02X" to get uppercase hex-digits.

Comments

1

You can use something like this:

char * append_hex(char *out, uint8_t value)
{
  static const char digits[] = "0123456789abcdef";
  *out++ = digits[value >> 4];
  *out++ = digits[value & 0xf];
  return out;
}

Then just call that in a loop, passing the returned value from it on each successive call. You can add separators between the calls, if desired.

Remember to 0-terminate the string when done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.