Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Byte Array to hex string in visual c++?

Declaration of a method are following:

//some.h
void TDES_Decryption(BYTE *Data, BYTE *Key, BYTE *InitalVector, int Length);

I am calling this method from the following code:

//some.c
extern "C" __declspec(dllexport) bool _cdecl OnDecryption(LPCTSTR stringKSN, LPCTSTR BDK){
    TDES_Decryption(m_Track1Buffer, m_cryptoKey, init_vector, len);
    return m_Track1Buffer;
}

Where as data type of m_Track1Buffer is BYTE m_Track1Buffer[1000]; Now i want to make some changes in above method i.e. want to return the String in hex instead of Byte. How should i convert this m_Track1buffer to Hex string

like image 373
Amit Pal Avatar asked Dec 27 '12 06:12

Amit Pal


People also ask

How do you convert a byte array to a hexadecimal string in C?

To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st . This is a relatively slower process for large byte array conversion.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

Can we convert byte to string in C#?

We can use Encoding. GetString Method (Byte[]) to decodes all the bytes in the specified byte array into a string. Several other decoding schemes are also available in Encoding class such as UTF8, Unicode, UTF32, ASCII etc. The Encoding class is available as part of System.


2 Answers

As you have mentioned c++, here is an answer. Iomanip is used to store ints in hex form into stringstream.

#include <sstream>
#include <iomanip>

std::string hexStr(BYTE *data, int len)
{
     std::stringstream ss;
     ss << std::hex;

     for( int i(0) ; i < len; ++i )
         ss << std::setw(2) << std::setfill('0') << (int)data[i];

     return ss.str();
}
like image 55
2r2w Avatar answered Sep 18 '22 14:09

2r2w


This code will convert byte array of fixed size 100 into hex string:

BYTE array[100];
char hexstr[201];
int i;
for (i=0; i<ARRAY_SIZE(array); i++) {
    sprintf(hexstr+i*2, "%02x", array[i]);
}
hexstr[i*2] = 0;
like image 45
mvp Avatar answered Sep 17 '22 14:09

mvp