Skip to content

Commit f3fd0ea

Browse files
committed
Use bit-cast for rgb565 conversion to/from uint16_t
1 parent 194cb9e commit f3fd0ea

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

util/colors_rgb565.hh

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,32 +32,31 @@ struct RGB565 {
3232

3333
// Construct from raw u16 RGB565 format
3434
RGB565 operator=(uint16_t raw) {
35-
std::memcpy(this, &raw, 2);
35+
*this = std::bit_cast<RGB565>(raw);
3636
return *this;
3737
}
3838

39-
// Returns endianness with r as MSB
4039
constexpr uint16_t raw() const {
4140
return (r << 11) | (g << 5) | b;
4241
}
4342

4443
constexpr operator uint16_t() const {
45-
return raw();
44+
return std::bit_cast<uint16_t>(*this);
4645
}
4746

4847
//0..255
4948
constexpr uint8_t red() const {
50-
return (raw() & 0xf800) >> 8;
49+
return r << 3;
5150
}
5251

5352
//0..255
5453
constexpr uint8_t green() const {
55-
return (raw() & 0x07e0) >> 3;
54+
return g << 2;
5655
}
5756

5857
//0..255
5958
constexpr uint8_t blue() const {
60-
return (raw() & 0x001f) << 3;
59+
return b << 3;
6160
}
6261
};
6362
namespace Colors565
@@ -89,4 +88,4 @@ static_assert(RGB565{(uint8_t)0xFF, 0xFF, 0xFF}.raw() == 0xFFFF);
8988
static_assert(RGB565{(uint8_t)0x80, 0x80, 0x80}.raw() == 0x8410);
9089
static_assert(RGB565{(uint8_t)0x00, 0x00, 0x00}.raw() == 0x0000);
9190

92-
static_assert(RGB565(0xFFAA22) == RGB565((uint8_t)0xFF, 0xAA, 0x22));
91+
static_assert(RGB565(0xFFAA22).raw() == RGB565((uint8_t)0xFF, 0xAA, 0x22).raw());

0 commit comments

Comments
 (0)