Reputation: 4693
Here is what I currently have so far:
void WriteHexToFile( std::ofstream &stream, void *ptr, int buflen, char *prefix )
{
unsigned char *buf = (unsigned char*)ptr;
for( int i = 0; i < buflen; ++i ) {
if( i % 16 == 0 ) {
stream << prefix;
}
stream << buf[i] << ' ';
}
}
I've tried doing stream.hex, stream.setf( std::ios::hex ), as well as searching Google for a bit. I've also tried:
stream << stream.hex << (int)buf[i] << ' ';
But that doesn't seem to work either.
Here is an example of some output that it currently produces:
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í
I would like the output to look like the following:
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
Upvotes: 17
Views: 47787
Reputation:
#include <iostream>
int main() {
char c = 123;
std::cout << std::hex << int(c) << std::endl;
}
Edit: with zero padding:
#include <iostream>
#include <iomanip>
int main() {
char c = 13;
std::cout << std::hex << std::setw(2) << std::setfill('0') << int(c) << std::endl;
}
Upvotes: 32
Reputation: 5969
You can also do it using something a bit more old-fashioned:
char buffer[4];//room for 2 hex digits, one extra ' ' and \0
sprintf(buffer,"%02X ",onebyte);
Upvotes: 1
Reputation: 379
CHAR to wchar_t (unicode) HEX string
wchar_t* CharToWstring(CHAR Character)
{
wchar_t TargetString[10];
swprintf_s(TargetString, L"%02X", Character);
// then cut off the extra characters
size_t Length = wcslen(TargetString);
wchar_t *r = new wchar_t[3];
r[0] = TargetString[Length-2];
r[1] = TargetString[Length-1];
r[2] = '\0';
return r;
}
Upvotes: 0
Reputation: 3341
I usually make a function which returns the digits and just use it:
void CharToHex(char c, char *Hex)
{
Hex[0]=HexDigit(c>>4);
Hex[1]=HexDigit(c&0xF);
}
char HexDigit(char c)
{
if(c<10)
return c;
else
return c-10+'A';
}
Upvotes: 0
Reputation: 264461
Try:
#include <iomanip>
....
stream << std::hex << static_cast<int>(buf[i]);
Upvotes: 2
Reputation: 6128
You simply need to configure your stream once:
stream << std::hex << std::setfill('0') << std::setw(2)
Upvotes: -1
Reputation: 108899
char upperToHex(int byteVal)
{
int i = (byteVal & 0xF0) >> 4;
return nibbleToHex(i);
}
char lowerToHex(int byteVal)
{
int i = (byteVal & 0x0F);
return nibbleToHex(i);
}
char nibbleToHex(int nibble)
{
const int ascii_zero = 48;
const int ascii_a = 65;
if((nibble >= 0) && (nibble <= 9))
{
return (char) (nibble + ascii_zero);
}
if((nibble >= 10) && (nibble <= 15))
{
return (char) (nibble - 10 + ascii_a);
}
return '?';
}
More code here.
Upvotes: 7