开发者

Convert hexadecimal charArray to String

开发者 https://www.devze.com 2023-02-16 22:47 出处:网络
I have a serious and irritating problem, please help mdContext->digest[i] is an unsigned char Array with hexadecimal values so

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 h开发者_运维知识库elp 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


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;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号