Convert array to string

This is a discussion on Convert array to string within the C Programming forums, part of the General Programming Boards category; I have the following code and need to convert the array into character string and print the value later as ...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    13

    Convert array to string

    I have the following code and need to convert the array into character string and print the value later as opposed to printing it via loop:

    int main( void )
    {
    int i;
    unsigned char buf[16]; // assume buf is populated by a function.
    char p[33];

    for( i = 0; i < 16; i++ )
    printf( "%02x", digest[i] );

    return( 0 );
    }

    how can I place the characters from buf into p?
    Thanks in advance.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    There is a version of printf that prints to a string....

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You could have some fun with strcat + sprintf.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    13
    This is how I did it using macro:

    #define arrayToString(name, digest) { char p[3]; int i; \
    for( i = 0; i < 16; i++ ){ \
    sprintf(p, "%02x", digest[i]); \
    strcat(name, p); \
    }}

    but I was looking for a faster/optimized solution.
    Thanks for everybody's feedback.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    If you want "optimized", note that you know where each print is supposed to go (since you have a fixed width print), hence there's no need to use strcat to find the end of the old string -- you know where it is, so you can print directly where it's supposed to go.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  3. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21