Question

I use CPPUNIT_ASSERT_EQUAL(a, b) to check the value a and b. The a and b are unsigned char type. So, when this assertion failed it will display the expected and actual value. Because the type is unsigned char, the expected and actual value will be displayed as characters. For example, 35 will be displayed as #. But this is not what I want. Of course, CPPUNIT_ASSERT_EQUAL((int)a, (int)b) may be a solution but it looks like strange. In addition, it would be better if the values are displayed as hex format. But I don't know how to reach this. It would be highly appreciated if somebody gives a answer.

Was it helpful?

Solution

I'd think the only way to achieve this effect is to adapt a and/or b with a suitable type which does the required comparison but is formatted differently than unsigned char. This could look something like this:

template <typename T>
struct as_hex_t
{
    as_hex_t(T const& value): d_value(value) {}
    T const& d_value;
};
bool operator== (as_hex_t<T> const& v0, as_hex_t<T> const& v1) {
    return v0.d_value == v1.d_value;
}
std::ostream& operator<< (std::ostream& out, as_hex_t const& value) {
    return out << std::hex << unsigned(value.d_value) << std::dec;
}
template <typenane T>
as_hex_t<T> as_hex(T const& val) { return as_hex_t<T>(val); }

CPPUNIT_ASSERT_EQUAL(as_hex(a), as_hex(b));

Obviously, the type to adapt the values is just needed to be defined once in a suitable place and can go into a suitable macro. I don't know CPPUNIT but I could image that something like this exists somewhere.

OTHER TIPS

Add #include <cstdio> and use printf function. (printf reference).

Use the %x or %X to display the number as a hexadecimal. the example from the link above shows you, that printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);

Gives the output,

Some different radixes: 100 64 144 0x64 0144

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top