Arduino:将字符串十六进制“#FFFFFF”转换为3 int

时间:2014-05-10 03:35:54

标签: c++ c arduino hex

我对C / C ++完全陌生,我试图弄清楚如何转换一个字符串参数,该参数将采用html样式rgb hex的形式,例如" #ffffff"并将其转换为3个整数变量

我真的不知道该去哪儿。

3 个答案:

答案 0 :(得分:13)

您需要做的就是将字符串转换为整数,然后将它们分成三个独立的r,g,b值。

string hexstring = "#FF3Fa0";

// Get rid of '#' and convert it to integer
int number = (int) strtol( &hexstring[1], NULL, 16);

// Split them up into r, g, b values
int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;

您也可以查看this question


编辑(感谢James评论):

对于某些机器(例如Arduino(Uno)),整数是16位而不是32位。如果红色值正在下降,请使用长整数。

string hexstring = "#FF3Fa0";

// Get rid of '#' and convert it to integer
long number = strtol( &hexstring[1], NULL, 16);

// Split them up into r, g, b values
long r = number >> 16;
long g = number >> 8 & 0xFF;
long b = number & 0xFF;

修改(更安全的版本,使用strtoll代替strtol):

long long number = strtoll( &hexstring[1], NULL, 16);

// Split them up into r, g, b values
long long r = number >> 16;
long long g = number >> 8 & 0xFF;
long long b = number & 0xFF;

答案 1 :(得分:2)

首先,您需要解析您的价值。你可以这样做:

void parse_hex(char* a, char* b, char* c, const char* string) {
    //certainly not the most elegant way. Note that we start at 1 because of '#'
    a[0] = string[1];
    a[1] = string[2];
    b[0] = string[3];
    b[1] = string[4];
    c[0] = string[5];
    c[1] = string[6];
}

然后,您将每个字符串转换为它的对应整数。您可以从this回答了解如何执行此操作。

答案 2 :(得分:0)

#include <stdlib.h>
#include <iostream>

int main()
{
   char const* str = "#FF9922";
   char red[5] = {0};
   char green[5] = {0};
   char blue[5] = {0};

   red[0] = green[0] = blue[0] = '0';
   red[1] = green[1] = blue[1] = 'X';

   red[2] = str[1];
   red[3] = str[2];

   green[2] = str[3];
   green[3] = str[4];

   blue[2] = str[5];
   blue[3] = str[6];

   int r = strtol(red, NULL, 16);
   int g = strtol(green, NULL, 16);
   int b = strtol(blue, NULL, 16);

   std::cout << "Red: " << r << ", Green: " << g << ", Blue: " << b << std::endl;
}