Skip to content

Instantly share code, notes, and snippets.

@gregoryfmartin
Last active November 12, 2022 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregoryfmartin/88059a2d11f6246ebf43b89e3fb55f2f to your computer and use it in GitHub Desktop.
Save gregoryfmartin/88059a2d11f6246ebf43b89e3fb55f2f to your computer and use it in GitHub Desktop.
Linux Colored Terminal String (24-bit)
#include <string>
#include <iostream>
#include <sstream>
#include <cstdint>
#include <tuple>
/*
* It's still not too obvious to me why this is the case, but when trying to use uint8_t here instead of uint16_t for the tuples,
* this resulted in the string not being colored. Changing this to uint16_t allowed the string to be colored successfully.
*/
const std::string build_colored_term_str(const std::tuple<uint16_t, uint16_t, uint16_t>& fgc, const std::tuple<uint16_t, uint16_t, uint16_t>& bgc, const std::string& str) {
std::stringstream ss;
ss << "\033[38;2;" << std::get<0>(fgc) << ";" << std::get<1>(fgc) << ";" << std::get<2>(fgc) << "m\033[48;2;" << std::get<0>(bgc) << ";" << std::get<1>(bgc) << ";" << std:: get<2>(bgc) << "m" << str << "\033[m";
return ss.str();
}
int main(int argc, char** argv) {
std::cout << build_colored_term_str(std::make_tuple<uint16_t, uint16_t, uint16_t>(175, 0, 255), std::make_tuple<uint16_t, uint16_t, uint16_t>(255, 255, 255), "Hello world in color!") << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment