I am using the following function to convert a byte array (Crypto++ key) to a Hex String
std::string Hexa::byte_to_hex_encoder(unsigned char *array, int len){
std::stringstream ss;
for(int i=0;i<len;++i)
ss << std::hex << std::uppercase <<std::setw(2) <<(int)array[i];
return ss.str();
}
The byte array is of size 16 and when I don't use setw(2)
I get a hex string with lesser characters like 30 or sometimes 31. When I am using setw(2)
I get random spaces in the hex string like
5CA0 138C5487D2C6D929EC36B694890
How can I convert a byte array to hex string and vice versa without spaces in the hex string?
You also need setfill('0')
so that the numbers are properly padded.
Without the setw
, a number like 7 comes out as just 7
, making your string short as you have seen. With the setw
but no setfill
, it's padded to the right length, but with a space.
Adding the setfill
ensures it gets padded with zeroes.
For your code that would be:
ss << std::hex
<< std::uppercase
<< std::setw(2)
<< std::setfill('0')
<< (int)array[i];
Since you have the Crypto++ tag, here's are two ways to do it in Crypto++. From the HexEncoder wiki page.
First, using Crypto++ pipelines :
byte decoded[] = { 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88,
0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 };
string encoded;
StringSource ss(decoded, sizeof(decoded), true,
new HexEncoder(
new StringSink(encoded)
) // HexEncoder
); // StringSource
cout << encoded << endl;
As with the previous example, a run produces the following output.
$ ./cryptopp-test.exe
FFEEDDCCBBAA99887766554433221100
And second, using functions:
byte decoded[] = { 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88,
0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 };
string encoded;
HexEncoder encoder;
encoder.Put(decoded, sizeof(decoded));
encoder.MessageEnd();
word64 size = encoder.MaxRetrievable();
if(size)
{
encoded.resize(size);
encoder.Get((byte*)encoded.data(), encoded.size());
}
cout << encoded << endl;
A run of the above program produces the following output.
$ ./cryptopp-test.exe
FFEEDDCCBBAA99887766554433221100
There's a HexDecoder too so you can decode the encoded strings. It works nearly the same way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.