2014-05-10 11 views

risposta

13

Tutto ciò che devi fare è convertire la stringa in numeri interi e quindi dividerli in tre valori separati di 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; 

Si consiglia di dare un'occhiata a this question pure.


Edit (grazie a James commenti):

Per qualche macchina (ad es Arduino (Uno)), int sono 16 bit invece di 32. Se i valori rossi sono in calo per te, utilizzare un lungo invece.

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; 

Edit (una versione ancora più sicura, utilizzare strtoll invece di 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; 
+0

Questo sembra il migliore per me finora, ma il problema è che' m iniziando con un tipo di String e sto diventando impossibile convertire 'String' in 'const char *' –

+0

Puoi convertire una stringa in 'const char *' dalla seguente stringa 'v1 = "# FF3Fa0"; const char * v2 = v1.c_str() '. Inoltre, questo '& hexstring [1]' significa semplicemente che prendi l'indirizzo di 'hexstring [1]', non importa se è 'stringa' o' const char * '. Ho modificato la risposta. –

+2

Grazie per la risposta Yuchen! Voglio notare che per i miei Arduino (Uno) int sono 16 bit invece di 32. Se i valori rossi stanno calando per te, prova a usare un long invece. – James

2

In primo luogo, è necessario analizzare il valore. Puoi farlo in questo modo:

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]; 
} 

Quindi, convertirai ogni stringa nel suo intero corrispondente. Puoi imparare come farlo dalla risposta this.

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; 
}