Home > Enterprise >  comparing bytes in google unit test framework
comparing bytes in google unit test framework

Time:05-06

I have a following test case where I want to compare bytes in google test. In Unity unit test frame work we have

TEST_ASSERT_BYTES_EQUAL(0xaa, output[4]);

Is similar ASSERT available in google test. I have following code in google test and test case failing.

TEST(sprintf, NoBufferOverRunsForNoFormatOperations) {
    char output[5];
    memset(output, 0xaa, sizeof output);
    ASSERT_EQ(3, sprintf_s(output, "hey"));
    ASSERT_STREQ("hey", output);
    ASSERT_THAT(0xaa, output[4]);
}

Failed log

[ RUN      ] sprintf.NoBufferOverRunsForNoFormatOperations
 Value of: 0xaa
Expected: is equal to -86
  Actual: 170 (of type int)
[  FAILED  ] sprintf.NoBufferOverRunsForNoFormatOperations (0 ms)

Any clues and help are welcome.

CodePudding user response:

The problem is that you are comparing 0xaa, a literal of type int with a value of decimal 170, with the value of output[4] which is itself of type char. char is a signed type in C and C . You wrote 0xaa or binary 10101010 into the byte in question. Because it is interpreted as a signed number, the leading 1 is considered as the sign bit in two's complement (which is undefined behavior up until C 20 I think) which gives it a value of -86 = 170 - 256.

  • Related