ProGirlXOXO
ProGirlXOXO

Reputation: 2300

Convert Integer to Little Endian Hex String

I'm trying to convert an integer to a little endian hex string. I can get to a little endian hex long but I'm not sure how to convert to string from there.

int iNum = 17706; 
// convert to long little endian hex
long lNum = (long)_byteswap_ushort(iNum);
// convert to string??

Alternatively, is there a way to go straight from an integer to little endian hex string?

Thanks.

Upvotes: 0

Views: 4137

Answers (2)

Pete Becker
Pete Becker

Reputation: 76370

For a portable solution, just mask and shift:

while (iNum != 0) {
    int byte = iNum & 0x0F;
    std::cout << std::hex << byte;
    iNum /= 16;
}

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63830

Use std::stringstream to format strings.

Also, use _byteswap_ulong or large ints will not be accurate.

long iNum = 17706; 
// convert to long little endian hex
long lNum = (long)_byteswap_ulong(iNum);
// convert to string
std::ostringstream oss;
oss << std::hex << lNum;
std::string mystring = oss.str();

Upvotes: 1

Related Questions