1

私はしばらくの間、埋め込み C++ でこれを行う方法を考え出そうとしていました。RGB888 の Web サイトの 16 進数の色を持っています。 0x177C

現在、文字列から # を削除しましたが、RGB555 の作成に使用できる型に変換するのに苦労しています。

私のコードは現在次のようになっています

 p_led_struct->color = "#ba00ff";
 char hexString[7] = {};
 memmove(hexString, p_led_struct->color+1, strlen(p_led_struct->color));
 byte colorBytes[3];
 sscanf(hexString,"%x%x%x",&colorBytes);

colorBytes 配列に不正なデータがありますが、hexString 値は正しく「ba00ff」になります。

この変換をどのように行うべきかについての支援は素晴らしいでしょう:)

ありがとう!

4

3 に答える 3

2

問題は次のsscanf(hexString,"%x%x%x",&colorBytes);とおりです。

  1. sscanfパラメータとして3 を指定する必要intがありますが、指定された配列は 1 つだけであり、そうではありませんint
  2. シングル%xは 2 文字以上を読み取ります。

試す:

int r, g, b;
if(sscanf(hexString,"%2x%2x%2x", &r, &g, &b) != 3) {
     // error
}

編集:

scanf-family に関する非常に役立つ情報: http://en.cppreference.com/w/c/io/fscanf

于 2013-10-01T12:25:48.200 に答える
2

p_led_struct->color整数に変換

p_led_struct->color = "#ba00ff";
unsigned int colorValue = strtoul(p_led_struct->color+1, NULL, 16);

この RGB 値を RGB555 に変換します。RGB 整数にはフィールド 0000.0000.rrrr.rrrr.gggg.gggg.bbbb.bbbb があり、RGB555 にはフィールド 0rrr.rrgg.gggb.bbbb があるため、必要なのはビット シフトだけです。

unsigned short rgb555 = ((colorValue & 0x00f80000) >> 9) +  // red
  ((colorValue & 0x0000f800) >> 7) +  // green
  ((colorValue & 0x000000f8) >> 3);  // blue
于 2013-10-01T12:37:49.290 に答える
1

修飾子を使用hhして、1 バイトに直接スキャンします。

p_led_struct->color = "#ba00ff";
byte colorBytes[3];
int result;
result = sscanf( p_led_struct->color, "#%2hhx%2hhx%2hhx", &colorBytes[0], 
    &colorBytes[1], &colorBytes[2]);
if (result != 3) {
  ; // handle problem
}

3 つの RGB 8 ビット バイトを正常にスキャンした後、3x5 ビットの結果を再計算します。

int r,g,b;
r = colorBytes[0] >> 3;
g = colorBytes[1] >> 3;
b = colorBytes[2] >> 3;
printf("%04X", (r << 10) | (g << 5) | (b << 0));
于 2013-10-01T12:30:45.680 に答える