1

0 から 255 までの範囲の整数を、数値の 16 進数表現を含む正確に 2 文字の文字列に変換するにはどうすればよいですか?

入力:180 出力:「B4」

私の目標は、Graphicsmagick でグレースケール カラーを設定することです。したがって、同じ例を使用すると、次の最終出力が必要になります。

「#B4B4B4」

色の割り当てに使用できるように: Color("#B4B4B4");

簡単なはずですよね?

4

3 に答える 3

2

その必要はありません。これはより簡単な方法です:

ColorRGB(red/255., green/255., blue/255.)
于 2011-05-21T14:55:49.330 に答える
1

次のように、C++ 標準ライブラリの IOStreams 部分のネイティブの書式設定機能を使用できます。

#include <string>
#include <sstream>
#include <iostream>
#include <ios>
#include <iomanip>

std::string getHexCode(unsigned char c) {

   // Not necessarily the most efficient approach,
   // creating a new stringstream each time.
   // It'll do, though.
   std::stringstream ss;

   // Set stream modes
   ss << std::uppercase << std::setw(2) << std::setfill('0') << std::hex;

   // Stream in the character's ASCII code
   // (using `+` for promotion to `int`)
   ss << +c;

   // Return resultant string content
   return ss.str();
}

int main() {
   // Output: "B4, 04"
   std::cout << getHexCode(180) << ", " << getHexCode(4); 
}

実例。

于 2011-05-21T14:52:57.007 に答える
0

フォーマット指定子を使用printfして使用します。%xまたは、strtol基数を 16 に指定します。

#include<cstdio>

int main()
{

    int a = 180;
    printf("%x\n", a);

    return 0;
}
于 2011-05-21T14:49:29.183 に答える