0

Here is a char array

char temp[] ={0x1f,0x2d,0x3c};

i want use the __android_log_print to print the temp ,how can convert it to "1f2d3c" and print it in one line without a for loop?

What i expected

enter image description here

Reality

enter image description here

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
log1000
  • 587
  • 5
  • 17

2 Answers2

0

If the array is always of size 3, then:

__android_log_print(<whatever level>,"%02x%02x%02x", temp[0],temp[1],temp[2]);
OldProgrammer
  • 12,050
  • 4
  • 24
  • 45
0

Substitute your log function for printf in the printHex function. You may be able to get away with not passing the length of the array as long as it is 0 terminated and there are no 0 bytes in the middle of it so you could use strlen to find the length.

#include <stdio.h>
#include <string.h>

void printHex(char* digits, int len)
{
    int i;
    char* str;

    str = malloc(len * 2 + 1);
    memset(str, 0, len * 2 + 1);
    for(i = 0; i < len; ++i)
    {
        char temp[3];
        sprintf(temp, "%02x", digits[i]);
        strcat(str, temp);
    }
    printf("%s\n", str);
    free(str);
}

int main(void) 
{
    char temp[] ={0x1f,0x2d,0x3c,4,0,5,0,6,7,8};
    printHex(temp, sizeof(temp));
    return 0;
}
Retired Ninja
  • 4,785
  • 3
  • 25
  • 35
  • Given the example values in his array, I would interpret it as raw binary data, in which 0-values may appears, and `strlen()` would be inappropriate. – Jonathon Reinhart Jan 05 '15 at 03:47
  • Also, an optimization: You could `sprintf(&str[2*i], ...` directly. This avoids the `strcat` every iteration, which is expensive, as it must scan of the end of the string *every time*. You could also leave out the `memset` then. – Jonathon Reinhart Jan 05 '15 at 03:49