[英]C/C++ Hex char* to byte array
I've been trying to work out how to do this in embedded C++ for a while now, I've got a hex colour for a website in RGB888 eg "#ba00ff" that I want to convert into a C++ RGB555 hex value, eg 0x177C 我一段时间以来一直在尝试如何在嵌入式C ++中执行此操作,对于RGB888中的网站,我有一个十六进制颜色,例如“#ba00ff”,我想将其转换为C ++ RGB555十六进制值,例如0x177C
Currently i've trimmed the # from the string and am stuck at converting it into a type I can use for creating the RGB555 目前,我已经从字符串中修剪了#,并一直坚持将其转换为可用于创建RGB555的类型
my code currently looks like 我的代码目前看起来像
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);
the hexString value becomes "ba00ff" correctly although the colorBytes array has incorrect data. 尽管colorBytes数组的数据不正确,hexString值仍正确变为“ ba00ff”。
any assistance on how I should do this conversion would be awesome :) 我应该如何进行此转换的任何帮助都将非常棒:)
Thanks! 谢谢!
Problems with sscanf(hexString,"%x%x%x",&colorBytes);
sscanf(hexString,"%x%x%x",&colorBytes);
are: 是:
sscanf
expects you to give 3 int
s as a parameter but only one array is given and it is not int
. sscanf
希望您给出3个int
作为参数,但只给出一个数组,而不是int
。 %x
reads more than 2 characters. 单个%x
读取超过2个字符。 Try: 尝试:
int r, g, b;
if(sscanf(hexString,"%2x%2x%2x", &r, &g, &b) != 3) {
// error
}
Edit: 编辑:
Very useful info on scanf-family: http://en.cppreference.com/w/c/io/fscanf 关于scanf系列的非常有用的信息: http : //en.cppreference.com/w/c/io/fscanf
Convert p_led_struct->color
to an integer 将p_led_struct->color
转换为整数
p_led_struct->color = "#ba00ff";
unsigned int colorValue = strtoul(p_led_struct->color+1, NULL, 16);
and convert this RGB value into RGB555. 并将此RGB值转换为RGB555。 The RGB integer has fields 0000.0000.rrrr.rrrr.gggg.gggg.bbbb.bbbb, and RGB555 has fields 0rrr.rrgg.gggb.bbbb, so we need only bit shifting: 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
Use hh
modifier to scan directly into 1 byte. 使用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
}
After you successfully scan the 3 RGB 8-bit bytes, recalculate the 3x5bit result. 成功扫描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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.