Site banner image, showing the newly started bind9 server for the domain you are visiting.

 22.08.2019 cpp

Using std::byte to write a color class

Why?

Because I can. No, really, there is no other explanation. I was reading up on Cxx17 and found out about std::byte, so I decided to find a use for it. This is the result. Remove the SDL_Color operator if you don’t want to use SDL.

Usage

The usage is really simple:

Color col("#12345678");

Here is the full code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**********************************************************************************
* _author  : Domeniko Gentner
* _mail    : code@tuxstash.de
* _license : This file has been placed in the Public Domain (CC0)
***********************************************************************************/
#pragma once


//-------------------------------------------------------------
struct Color
//-------------------------------------------------------------
{
	Color()
		: r{0x00}, b{0x00}, g{0x00}, a{0x00}
	{
	}

	Color(const std::string& col)
	{
		set(col);
	}

	void set(const std::string& col)
	{
		if (col.length() < 9) {
			LOG_ERROR("String too short");
			return;
		}
		color = col;
		r = std::byte(std::stoi(col.substr(1, 2), nullptr, 16));
		g = std::byte(std::stoi(col.substr(3, 2), nullptr, 16));
		b = std::byte(std::stoi(col.substr(5, 2), nullptr, 16));
		a = std::byte(std::stoi(col.substr(7, 2), nullptr, 16));
	}

	Uint8 red()
	{
		return std::to_integer<Uint8>(r);
	}

	Uint8 green()
	{
		return std::to_integer<Uint8>(g);
	}

	Uint8 blue()
	{
		return std::to_integer<Uint8>(b);
	}

	Uint8 alpha()
	{
		return std::to_integer<Uint8>(a);
	}

	operator std::string()
	{
		return color;
	}

	std::string& operator=(const std::string& s)
	{
		this->color = s;
		set(color);
		return this->color;
	}

	operator SDL_Color()
	{
		SDL_Color col = { red(), green(), blue(), alpha() };
		return col;
	}

	std::byte r;
	std::byte g;
	std::byte b;
	std::byte a;
	std::string color;
};

Link to the author's twitter Link to the authors ko-fi page

comments

Characters: 0/1000

gravatar portrait

 Pinned by contact@tuxstash.de

Come join the discussion and write something nice. You will have to confirm your comment by mail, so make sure it is legit and not a throwaway. Only the name part of it will be displayed, so don't worry about spam. If it does not show up after confirming it, it may be considered spam, but I curate them manually, so don't worry. Please read the privacy statement for more.