C / C ++ Hex char *到字节数组

时间:2013-10-01 12:15:28

标签: c++ c hex scanf

我一直试图在嵌入式C ++中尝试如何做一段时间,我已经为RGB888中的网站设置了十六进制颜色,例如“#ba00ff”,我想将其转换为C ++ RGB555十六进制值,例如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”。

关于如何进行此转换的任何帮助都很棒:)

谢谢!

3 个答案:

答案 0 :(得分:2)

sscanf(hexString,"%x%x%x",&colorBytes);的问题是:

  1. sscanf希望您提供3 int作为参数,但只提供一个数组且不是int
  2. 单个%x读取超过2个字符。
  3. 尝试:

    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

答案 1 :(得分: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

答案 2 :(得分: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位字节后,重新计算3x5bit结果。

int r,g,b;
r = colorBytes[0] >> 3;
g = colorBytes[1] >> 3;
b = colorBytes[2] >> 3;
printf("%04X", (r << 10) | (g << 5) | (b << 0));