fork(1) download
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. #define GET_COMPONENT(color, index) (((0xFF << (index * 8)) & color) >> (index * 8))
  5.  
  6. unsigned int get_component(unsigned int color, unsigned int index)
  7. {
  8. const unsigned int shift = index * 8;
  9. const unsigned int mask = 0xFF << shift;
  10. return (color & mask) >> shift;
  11. }
  12.  
  13. enum color_component
  14. {
  15. A,B,G,R
  16. };
  17.  
  18. unsigned int get_component(unsigned int color, color_component component)
  19. {
  20. switch (component)
  21. {
  22. case R:
  23. case G:
  24. case B:
  25. case A:
  26. {
  27. const unsigned int shift = component * 8;
  28. const unsigned int mask = 0xFF << shift;
  29. return (color & mask) >> shift;
  30. }
  31.  
  32. default:
  33. throw std::invalid_argument("invalid color component");
  34. }
  35.  
  36. return 0;
  37. }
  38.  
  39. int main(int argc, char **argv)
  40. {
  41. unsigned int the_color = 0xAABBCCFF;
  42. std::cout << std::hex << "With macro:\n"
  43. << "R: " << GET_COMPONENT(the_color, 3) << '\n'
  44. << "G: " << GET_COMPONENT(the_color, 2) << '\n'
  45. << "B: " << GET_COMPONENT(the_color, 1) << '\n'
  46. << "A: " << GET_COMPONENT(the_color, 0) << '\n';
  47.  
  48. std::cout << std::hex << "With function:\n"
  49. << "R: " << get_component(the_color, 3) << '\n'
  50. << "G: " << get_component(the_color, 2) << '\n'
  51. << "B: " << get_component(the_color, 1) << '\n'
  52. << "A: " << get_component(the_color, 0) << '\n';
  53.  
  54. std::cout << std::hex << "With function:\n"
  55. << "R: " << get_component(the_color, R) << '\n'
  56. << "G: " << get_component(the_color, G) << '\n'
  57. << "B: " << get_component(the_color, B) << '\n'
  58. << "A: " << get_component(the_color, A) << '\n';
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 2900KB
stdin
Standard input is empty
stdout
With macro:
R: aa
G: bb
B: cc
A: ff
With function:
R: aa
G: bb
B: cc
A: ff
With function:
R: aa
G: bb
B: cc
A: ff