Last active
November 22, 2023 19:48
-
-
Save juanfal/875fc61d88bcee2185179667bf08c8a0 to your computer and use it in GitHub Desktop.
rgb to hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// t11e21.rgbtohex.cpp | |
// juanfc 2023-11-22 | |
// | |
#include <iostream> | |
#include <array> | |
using namespace std; | |
typedef array<int,3> TRGB; | |
void test(TRGB rgb); | |
int main() | |
{ | |
test((TRGB){{255, 255, 255}}); // "FFFFFF" | |
test((TRGB){{255, 255, 300}}); // "FFFFFF" | |
test((TRGB){{0,0,0}}); // "000000" | |
test((TRGB){{148, 0, 211}}); // "9400D3" | |
return 0; | |
} | |
string rgb2hex(TRGB rgb); | |
void test(TRGB rgb) | |
{ | |
cout << rgb[0] << ", "; | |
cout << rgb[1] << ", "; | |
cout << rgb[2] << ": "; | |
cout << rgb2hex(rgb) << endl; | |
} | |
string int2str(int n, int base=10, int width=0); | |
string rgb2hex(TRGB rgb) | |
{ | |
string r; | |
for (int i = 0; i < 3; ++i) | |
r += int2str((rgb[i] > 255)? 255:rgb[i], 16, 2); | |
return r; | |
} | |
string int2str(int n, int base, int width) | |
{ | |
string r; | |
if (n == 0) { | |
r += '0'; | |
} else { | |
int sign = (n < 0) ? -1 : 1; | |
n *= sign; | |
while (n > 0) { | |
int remainder = n % base; | |
n /= base; | |
r += ((remainder < 10) ? '0' : 'A'-10) + remainder; | |
} | |
if (sign == -1) r += '-'; | |
} | |
for (int i = r.length(); i < width; ++i) | |
r += '0'; | |
// reversing | |
int j = r.size() - 1; | |
for (int i = 0; i < j; i++, j--) { | |
char t = r[i]; | |
r[i] = r[j]; | |
r[j] = t; | |
} | |
return r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment