2

I have a serious and irritating problem, please help

mdContext->digest[i] is an unsigned char Array with hexadecimal values so

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

prints 900150983cd24fb0d6963f7d28e17f72

now.... I want to get this value in a char Array, i.e if I do

printf("%s",ArrayConverted);

I want to print the above string... Please help me in doing this

Things I tried

Trial-1

unsigned char in[64]=0;
  int tempValue[64];
 

  for (i = 0; i < 16; i++){
      sprintf(&tempValue[i],"%02x", (unsigned char)mdContext->digest[i]);
          in[i]=(unsigned char)tempValue[i];
  }
  
 printf("%s\n\n\n",in);

This prints 90593d4bd9372e77 But Original content is 900150983cd24fb0d6963f7d28e17f72

So it is skipping many characters in between... please help me converting this hexadecimal Char array in to a String

1
  • change tempValue to a char array, vice int, and see what you get. Commented Mar 13, 2011 at 1:16

2 Answers 2

5
char tempValue[33]; // 32 hex digits + 0-terminator
int i;
for (i = 0; i < 16; ++i)
  sprintf(tempValue + 2*i, "%02x", (unsigned char)mdContext->digest[i]);

Each byte requires two hexadecimal digits - so adjust the start position for sprintf with 2*i

tempValue + 2*i is the same as &tempValue[2*i]

EDIT: A correct c++ version.

std::stringstream s;
for (int i = 0; i < 16; ++i) 
  s << std::hex << std::setfill('0') << std::setw(2) << (unsigned short) mdContext->digest[i];
std::cout << s.str() << std::endl;
Sign up to request clarification or add additional context in comments.

Comments

1

C++ specific solution:

    #include <sstream> 
    #include <iomanip>

    std::stringstream s;
    s.fill('0');
    for ( size_t i = 0 ; i < 16 ; ++i )
       s << std::setw(2) << std::hex <<(unsigned short)mdContext->digest[i]);
    std::cout << s.str() << endl;

Small demo : http://ideone.com/sTiEn

9 Comments

@Erik: Updated. See if it's fixed now.
@Nawaz: Don't you just hate streams :P - I'll remove comments now, please add the setfill as well
@Erik: Oops. Fixed that as well :D. BTW, why did you say "don't you just hate streams"? :-/
@Nawaz: Don't everyone hate streams? I mean, look at the syntax for simple printing of hex values... I'm usually very fond of C++ constructs, but the streams are, well, not the most clever part of the stdlib :P
@Erik: Yeah. Here it looks ugly. But sometimes it's really very smart. For example see the SECOND solution here in my post : stackoverflow.com/questions/4888879/…
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.