Expanding the inputs of String toHexString


#1

Recently I was trying to get a hex string for a uint32. It turns out String::toHexString is implemented for int, int64 and short. Would expanding it to this be useful to anyone?

String String::toHexString (const int number)            { return hexToString ((unsigned int) number); }
String String::toHexString (const unsigned int number)   { return hexToString (number); }
String String::toHexString (const short number)          { return toHexString ((int) (unsigned short) number); }
String String::toHexString (const unsigned short number) { return toHexString ((int) number); }
String String::toHexString (const int64  number)         { return hexToString ((uint64) number); }
String String::toHexString (const uint64 number)         { return hexToString (number); }
String String::toHexString (const long number)           { return hexToString ((unsigned long) number); }
String String::toHexString (const unsigned long number)  { return hexToString (number); }

String String::toHexString (const float  number)         { return hexToString (*reinterpret_cast<const uint32*>(&number)); }
String String::toHexString (const double number)         { return hexToString (*reinterpret_cast<const uint64*>(&number)); }

#2

Historically I avoided having this kind of set of overloads because IIRC there were problems with type ambiguities, mainly in older Visual Studio versions. I think it’s probably not so much of an issue now that we expect everyone to have compliant modern compilers, so it could indeed be time to add some more of these back in. (Or to find a nice way to template it to avoid some repetition)


#3

Anything wrong with something like the following? Seems to work for me here. I can convert all the things to hex.

template <typename Type>
static String toHexString (Type number)
{
    return toHexString ((void*)&number, sizeof(number), -1);
}

#4

…but the resulting hex representation will be wrong on all little-endian platforms (which are all those for which JUCE is compiled nowadays).

In addition, -1 does not seem like a valid value for the groupSize (third) parameter of toHexString(). You’re at risk of undefined behavior there.


#5

Yeah, I have a version I’ll push today that should handle the edge-cases.


#6

The edge cases like little endian.

My bad. :slight_smile: