Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino: Convert a String hex "#FFFFFF" into 3 int

Tags:

c++

c

hex

arduino

I'm completely new to C/C++ and I am trying to figure out how to convert a String argument that would be in the form of a html style rgb hex such as "#ffffff" and turn that into 3 integers vars

I'm really not sure where to being.

like image 278
Polygon Pusher Avatar asked May 10 '14 03:05

Polygon Pusher


People also ask

How to convert hex string to int in arduino?

To convert a hex string to int, you can use function strtol ( or strtoul if you want a unsigned result).

How do I use Atoi in Arduino?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.


1 Answers

All you need to do is convert the string to integers and then split them into three separate r, g, b values.

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;

You may want to have a look at this question as well.


Edit (thanks to James comments):

For some machine (e.g. Arduino (Uno)), ints are 16 bits instead of 32. If red values are dropping for you, use a long instead.

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 (an even safer version, use strtoll instead of 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;
like image 98
Yuchen Avatar answered Sep 29 '22 12:09

Yuchen