Pedro Junior
Pedro Junior

Reputation: 99

Concatenate 5 or more bytes and convert to decimal and then to ASCII

I've this array below:

dataIn[5] = 0x88;
dataIn[6] = 0x2A;
dataIn[7] = 0xC7;
dataIn[8] = 0x2B;
dataIn[9] = 0x00;
dataIn[10] = 0x28;

I need to convert those values to decimal because after that I need to convert the decimal values into ASCII and send to UART.

Eg:

|    Hexa      |      Decimal      | ASCII (I need to send this data to UART)
| 0x882AC72B00  | 584 833 248 000  | 35 38 34 38 33 33 32 34 38 30 30 30
| 0x5769345612  | 375 427 192 338  | 33 37 35 34 32 37 31 39 32 33 33 38

My problem: Those data should put all together and convert to decimal, but my compiler is just for 4 bytes and I don't know how to do this because I've 5 or more bytes ever.

Ps.: I'm using PIC18F46K80 and C18 compiler

[Edited]

Click here to see what happen when I try to use more than 4 bytes. This is my problem

Anyone could help me ?

Thanks in advance.

Upvotes: 2

Views: 281

Answers (2)

tonypdmtr
tonypdmtr

Reputation: 3225

Have you considered writing your own conversion function? Here's a working example that can be adjusted to any length.

WARNING: My C skills are not the best!

#include <stdio.h>

/******************************************************************************/

void base10_ascii(unsigned char data[], int data_size, char ans[], int ans_size) {
  char done;
  do {
    char r = 0;
    done = 1;
    for (int i=0; i<data_size; i++) {
      int b = (r<<8) + data[i]; //previous remainder and current byte
      data[i] = b / 10;
      if (data[i] > 0) done = 0; //if any digit is non-zero, not done yet
      r = b % 10;
    }
    for (int i=ans_size-1; i>0; i--) ans[i] = ans[i-1]; //bump up result
    ans[0] = r + '0'; //save next digit as ASCII (right to left)
  } while (!done);
}

/******************************************************************************/

int main(){
  char outputBuffer[15] = {0};
  char data[] = { 0x88, 0x2A, 0xC7, 0x2B, 0x00 }; //584833248000
  base10_ascii(data,sizeof data,outputBuffer,sizeof outputBuffer);
  printf("Output: %s\n",outputBuffer);
  return 0;
}

Upvotes: 0

LucaG
LucaG

Reputation: 84

If I have understood well, first of all you should define a union like this:

typedef union _DATA64
{
    uint64_t dataIn64;
    uint8_t dataIn8[8];
}tu_DATA64;

and then copy the hex values in the previous defined union:

uint8_t i;
tu_DATA64 data;

...

data.dataIn64=0;
for(i=0; i<5; i++)
    data.dataIn8[4-i]=dataIn[i];

now you have to convert the 64bit variable in a string using lltoa function, like suggested in this post:

char *str;

...

str=lltoa(data.dataIn64,10);

The str is the buffer string to send.

Upvotes: 0

Related Questions