1

As written in the title, I need to convert an (char) array containing 8 bytes(which represent a 64bit int) to a string. I'm using c code on a NEC78K0R (16 bit mcu). I'm using the IAR Embedded workbench IDE.

My thought was to OR them together in a 64 bit int type (like f.x long long or int64_t (from stdint.h)), and then use something like sprintf to convert it to a string.

However the compiler will start spitting out errors like "the type 'long long' does not exist'. whenever I use any of the standard 64bit integer type.

Any help will be much appreciated.

  • Related topic (not entirely duplicate): http://stackoverflow.com/questions/9695720/how-do-i-convert-a-64bit-integer-to-a-char-array-and-back?rq=1 – Niels Keurentjes May 21 '13 at 14:10

3 Answers3

1

If the char array references a memory block of 8 bytes that are actually a true 64-bit integer, and your compiler supports int64_t, you can just cast and dereference.

int64_t convert(const char* input)
{
    return *((int64_t*)input);
}

If the platform supports 64-bit data types, sprintf will also support it with the %L format specifier.

If your compiles does not support any 64-bit data types, you'll need to use a specific library to handle them for you, like BigInt or GMPlib.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
0

If long is the appropriate 32bit integer type and hex format would be ok, just do

char * p = <address of some memory containing a true 64bit number>
char s[19];

for a Little Endian platform:

sprintf(s, "0x%08x%08x, *((long*)(p+4)), *((long*)(p)));

for a Big Endian platform:

sprintf(s, "0x%08x%08x, *((long*)(p)), *((long*)(p+4)));
alk
  • 69,737
  • 10
  • 105
  • 255
0

You didn't specify the encoding of the string that you would need. The simplest would probably be to use hex encoding and just print the bytes directly.

printf("0x%02x%02x%02x%02x%02x%02x%02x%02x", a[7], a[6], a[5], a[4], a[3], a[2], a[1], a[0]);

To make this a bit more efficient, if that is a bottleneck for you, you could just group the maximal parts that your platform supports, by casting it to an unsigned long e.g. But be careful if your char array fulfills the necessary alignment to be interpreted as such an unsigned long. If you can't guarantee that, you should first use memcpy to copy the data to a properly aligned object.

unsigned long b[2];
memcpy(b, a, sizeof b);
printf("0x%08x%08x", b[1], b[0]);

(supposing that unsigned long is 4 bytes)

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177