Skip to content

Instantly share code, notes, and snippets.

@0xdw
Created February 20, 2021 13:02
Show Gist options
  • Save 0xdw/1dbcdfd56a8f019ad2a595e6df10f647 to your computer and use it in GitHub Desktop.
Save 0xdw/1dbcdfd56a8f019ad2a595e6df10f647 to your computer and use it in GitHub Desktop.
C++ RGB to HEX Converter
// RGB_TO_HEX.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <string>
#define CHECK_FOR_RANGE(channel) \
if (channel > 255) { \
std::cerr << "Invalid " << #channel << " channel" << std::endl; \
exit(0); \
}
void get_values(int& R, int& G, int& B);
unsigned long get_hex(int R, int G, int B);
int main() {
// RGB
int R = 0;
int G = 0;
int B = 0;
get_values(R, G, B);
std::cout << "rgb(" << R << ", " << G << ", " << B << ")" << std::endl;
unsigned long hex = get_hex(R, G, B);
std::cout << "#" << hex << std::endl;
return 0;
}
void get_values(int& R, int& G, int& B) {
std::cout << "R: ";
std::cin >> R;
CHECK_FOR_RANGE(R)
std::cout << "G: ";
std::cin >> G;
CHECK_FOR_RANGE(G)
std::cout << "B: ";
std::cin >> B;
CHECK_FOR_RANGE(B)
}
unsigned long get_hex(int R, int G, int B) {
return ((R & 0xff) << 16) + ((G & 0xff) << 8) + (B & 0xff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment