Home > Blockchain >  How to unit test bit manipulation logic
How to unit test bit manipulation logic

Time:03-12

I have a method which converts RGBA to BGRA. Below is the method

unsigned int ConvertRGBAToBGRA(unsigned int v) {
    unsigned char r = (v)& 0xFF;
    unsigned char g = (v >> 8) & 0xFF;
    unsigned char b = (v >> 16) & 0xFF;
    unsigned char a = (v >> 24) & 0xFF;
    return (a << 24) | (r << 16) | (g << 8) | b;
};

How can I unit test this nicely? Is there a way I can read back the bits and unit test this method somehow?

I am using googletests

CodePudding user response:

You can split the value in four bytes by mapping to an array via a pointer. Then swap the bytes.

uint8_t* pV= reinterpret_cast<uint8_t*>(&V);
uint8_t Swap= pV[1]; pV[1]= pV[3]; pV[3]= Swap;

CodePudding user response:

Inspired by @Yves Daoust's comment, why can't you just write a series of checks like below? You can use the nice formatting of C 14:

unsigned int ConvertRGBAToBGRA(unsigned int v) {
  unsigned char r = (v)&0xFF;
  unsigned char g = (v >> 8) & 0xFF;
  unsigned char b = (v >> 16) & 0xFF;
  unsigned char a = (v >> 24) & 0xFF;
  return (a << 24) | (r << 16) | (g << 8) | b;
};

TEST(ConvertRGBAToBGRATest, Test1) {
  EXPECT_EQ(ConvertRGBAToBGRA(0x12'34'56'78), 0x12'78'56'34);
  EXPECT_EQ(ConvertRGBAToBGRA(0x12'78'56'34), 0x12'34'56'78);
  EXPECT_EQ(ConvertRGBAToBGRA(0x11'11'11'11), 0x11'11'11'11);
  EXPECT_EQ(ConvertRGBAToBGRA(0x00'00'00'00), 0x00'00'00'00);
  EXPECT_EQ(ConvertRGBAToBGRA(0xAa'Bb'Cc'Dd), 0xAa'Dd'Cc'Bb);

  EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x12'34'56'78)), 0x12'34'56'78);
  EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x12'78'56'34)), 0x12'78'56'34);
  EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x11'11'11'11)), 0x11'11'11'11);
  EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0x00'00'00'00)), 0x00'00'00'00);
  EXPECT_EQ(ConvertRGBAToBGRA(ConvertRGBAToBGRA(0xAa'Bb'Cc'Dd)), 0xAa'Bb'Cc'Dd);
}

Live example: https://godbolt.org/z/eEajYYYsf

  • Related