C++ RGB To Hex Conversion(RGB转换16进制)(No.11)

要求:


rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3

解法一:

#include <iostream>
#include <string>
#include <sstream>
#include <cctype>

using namespace std;
class RGBToHex
{
  public:
  static std::string rgb(int r, int g, int b);
};

std::string RGBToHex::rgb(int r, int g, int b) {
  stringstream s;
  if (r > 255) r = 255;
  if (r < 0) r = 0;
  if (g > 255) g = 255;
  if (g < 0) g = 0;
  if (b > 255) b = 255;
  if (b < 0) b = 0;
  if (r < 16)
    s << hex << 0 << r;
  else
    s << hex << r;
  if (g < 16)
    s << hex << 0 << g;
  else
    s << hex << g;
  if (b < 16)
    s << hex << 0 << b;
  else
    s << hex << b;
  string s_r;
  s >> s_r;
  for (unsigned int i = 0; i < s_r.size(); i++)
    if (s_r[i] >= 'a' && s_r[i] <= 'z')
      s_r[i] = s_r[i] - 32;
  return s_r;
}

优秀解法:

using namespace std;
class RGBToHex
{
  public:
  static std::string rgb(int r, int g, int b){
        stringstream ss;
    char c[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    if(r<0) r=0;
    if(g<0) g=0;
    if(b<0) b=0;
    if(r>255) r=255;
    if(g>255) g=255;
    if(b>255) b=255;
    ss<<c[(int)r/16]<<c[r%16]<<c[(int)g/16]<<c[g%16]<<c[(int)b/16]<<c[b%16];
  return ss.str();
  }
};

优秀解法二:

#include <algorithm>
#include <cstdio>

namespace RGBToHex
{
    std::string rgb(int r, int g, int b)
    {
        char result[7];
        std::sprintf(result, "%02X%02X%02X",
            std::clamp(r, 0, 255),
            std::clamp(g, 0, 255),
            std::clamp(b, 0, 255));
        return result;
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值