Hexadecimal for RGB

Asked

Viewed 1,690 times

15

How to convert a Hexadecimal color (#FFFFFF) for RGB (Red, GReen, BLue)?

Example

  • I didn’t put language tag, because by my search on the site, you don’t have this content, the closest I found was this. If anyone else wants to answer in another language.

  • 5

    If you are not interested in a specific language, how about putting independente-de-linguagem and accept a pseudo-code response or explain the algorithm without involving code (such as the response of the Rcoster for example)? In my opinion, the way it is (each one responding in a different language) the question is very broad, it is difficult to choose an answer to accept. It’s kind of like a mix list with code-golf rsrs.

  • 1

    @mgibsonbr also got a strange feeling about the question (although I myself got into the joke). You raising the fact that it looks like a list makes me think it’s really a case to close.

  • @mgibsonbr, my intention was to create a repositories with functions already tips, then each one contributed with its language. But yes the answer I would adopt by this criterion.

  • 2

    @Guilhermelautert I suggest you take a look at the post of the goal 'How can we deal with "lists"?' in case you haven’t already. What you want to do is something quite desirable on the site, but no one knows yet how to do it well, so it became a kind of "taboo" here... Let’s see how the community reacts, the question is not bad, there have been others... :)

  • @mgibsonbr will take me a while to read everything here, but I will do it : D

Show 1 more comment

7 answers

18


It is more a question of computational mathematics/mathematics than programming. Follow my contribution:

The RGB code, as the name says, consists of 3 elements: Red, Green and Blue. In this case, the format #ffffff is a hexadecimal representation of the color code, where each two letters represent a color (in order). To 'translate' this number, we must make a base change - from hexadecimal (16), to decimal (10).

The first 10 hexadecimal numbers are equal to the decimal basis (0 to 9), the remaining 6 are (and their decimal representation): A (10); B (11); C (12); D (13); E (14) and F (15).

The base conversion should be done type by digit of each color, from right to left. For example:

#ffffff:
ff = 15 * 16 ^ 0 + 15 * 16 ^ 1 = 15 * 1 + 15 * 16 = 255
Portanto, em decimal, é (255, 255, 255)

#f5ffff
f5 = 5 * 16 ^ 0 + 15 * 16 ^ 1 = 5 * 1 + 15 * 16 = 245
ff = 15 * 16 ^ 0 + 15 * 16 ^ 1 = 15 * 1 + 15 * 16 = 255
Portanto, em decimal é (245, 255, 255)

11

In PHP

I withdrew the answer from here:

function hex2rgb($hex){
    $hex = str_replace("#", "", $hex);

    if(strlen($hex) == 3) {
        $r = hexdec(substr($hex,0,1).substr($hex,0,1));
        $g = hexdec(substr($hex,1,1).substr($hex,1,1));
        $b = hexdec(substr($hex,2,1).substr($hex,2,1));
    } else {
        $r = hexdec(substr($hex,0,2));
        $g = hexdec(substr($hex,2,2));
        $b = hexdec(substr($hex,4,2));
    }
    $rgb = array($r, $g, $b);
    //return implode(",", $rgb); // returns the rgb values separated by commas
    return $rgb; // returns an array with the rgb values
}
  • 3

    Note: This answer has something that others do not have, which is to take into consideration both 1 Nibble per color (e.g..: #fff) how much 1 byte per color (#ffffff).

11

In C#

var cor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
var corEmRgb = System.Drawing.Color.FromArgb(cor.R, cor.G, cor.B);

And to do it backwards

var cor = Color.FromArgb(255, 255, 255);
var hex = cor.R.ToString("X2") + cor.G.ToString("X2") + cor.B.ToString("X2");

10

Javascript

var rgb = ['001', '000', '255'];
var hex = '0100ff';

function converter(v) {
    if(typeof v === 'string') {
        var r = [];
    	v.match(/[0-9a-f]{2}/g).forEach(function(arr) {
        	r.push(('000' + parseInt(arr,16)).slice(-3));
        });
        return r;
    } else {
        var s;
    	v.forEach(function(arr) {
        	s = (s || '')  + ('00' + parseInt(arr,10).toString(16)).slice(-2);
        });
        return s;
    }
}

document.writeln('rgb: ' + converter(hex));
document.writeln('hex: ' + converter(rgb));

Reference from here

  • 3

    @devgaspa in my answer to another problem I’ve solved the problem from scratch to left in a way that’s kind of simple, if you’re curious to see it. I added up 256, and took the last 2 digits of the result.

  • @Bacco when I do it this way you did I don’t need to use Slice right ?

  • Cool, now it works.

  • @devgaspa I used substring (for lack of thing best hehehe)

8

Python

def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb
                                            # Resultados
print hex_to_rgb("#123456")                 # (18, 52, 86)
print hex_to_rgb("#ffffff")                 # (255, 255, 255)
print hex_to_rgb("#ffffffffffff")           # (65535, 65535, 65535)
print rgb_to_hex((18, 52, 86))              # #123456
print rgb_to_hex((255, 255, 255))           # #ffffff
print rgb_to_hex((65535, 65535, 65535))     # #ffffffffffff

See working on Ideone.

Source: Converting Hex color to RGB and vice versa

4

In C++

// Este programa não converte entre as bases decimal e hexadecimal
// Apenas altera a representação dos inteiros

#include <iostream>
using namespace std;

int main(){
    unsigned int hexadecimal[3]={0xFF,0xFF,0xFF};
    unsigned int decimal[3]={255,255,255};

    for (auto i:hexadecimal)
        cout << i << " ";

    cout << endl;

    for (auto j:decimal)
        cout << hex << j << " ";
    return 0;

}
  • 2

    Another way is, of course, to use any scientific calculator to convert between the various bases. The calculator itself that comes with Windows, for example, allows you to do this.

0

In Java

Using the class Color of java.awt just do:

Color color = Color.decode("#FFFFFF");

That gets the color corresponding to the value in hexadecimal. Then it is possible to obtain each RGB component of the resulting color through the methods:

  • getRed()
  • getGreen()
  • getBlue()

Example:

System.out.println(color.getRed()+" "+color.getGreen()+" "+color.getBlue()); //255 255 255

Source


Doing it manually looks more like the other answers:

String hex = "#FFFFFF";
int red =   Integer.parseInt(hex.substring(1 , 3), 16);
int green = Integer.parseInt(hex.substring(3 , 5), 16);
int blue =  Integer.parseInt(hex.substring(5 , 7), 16);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.