fork download
  1. #include <cmath>
  2. #include <cstdint>
  3. #include <stdexcept>
  4.  
  5. std::uint16_t SrgbToScrgb(std::uint8_t srgb)
  6. {
  7. auto x = static_cast<float>(srgb);
  8.  
  9. x /= 255.0f;
  10.  
  11. if (x <= 0.04045f) x /= 12.92f;
  12. else x = std::pow((x + 0.055f) / 1.055f, 2.4f);
  13.  
  14. x *= 8192.0f;
  15. x += 4096.0f;
  16.  
  17. return static_cast<std::uint16_t>(x + 0.5f);
  18. }
  19.  
  20. std::uint8_t ScrgbToSrgb(std::uint16_t scrgb)
  21. {
  22. auto x = static_cast<float>(scrgb);
  23.  
  24. x -= 4096.0f;
  25. x /= 8192.0f;
  26.  
  27. if (x <= 0.0031308f) x *= 12.92f;
  28. else x = 1.055f * std::pow(x, 0.41666f) - 0.055f;
  29.  
  30. x *= 255.0f;
  31.  
  32. return static_cast<std::uint8_t>(x + 0.5f);
  33. }
  34.  
  35. int main()
  36. {
  37. for (unsigned i = 0; i != 256; ++i)
  38. {
  39. auto scrgb = SrgbToScrgb(i);
  40. auto srgb = ScrgbToSrgb(scrgb);
  41. if (srgb != i) throw std::runtime_error{"Unable to perform lossless conversion"};
  42. }
  43. }
Success #stdin #stdout 0s 3336KB
stdin
Standard input is empty
stdout
Standard output is empty