3

I'm reading hex colors from a JSON file, but need to get them as an int so I can create a color.

int col=Integer.parseInt("FF0000",16); 

returns 16711680

int c = unhex("FF0000");

returns 16711680

how do I do this?

Tessa Painter
  • 2,113
  • 2
  • 16
  • 21

5 Answers5

4

If you want to reinvent the wheel, you could parse out the string into RGB hex values "FF", "00", and "00", convert the hex values to integers (255, 0, and 0 respectively) corresponding to int values from 0-255, and then create a Color object with those RGB values.

Personally though, I'd just use:

Color red = Color.decode("#FF0000"); //That's definitely red
dr3wmurphy
  • 186
  • 1
  • 7
1

You're conflating two things:

Thing one: Hex values like #FF0000 represent integer values.

Thing two: Internally, Processing represents color values as integers.

The integers in the first concept are not the same thing as the integers in the second concept.

In fact, hex color values are a special case in Processing of the Processing editor doing some magic for you. I don't know of a way to go directly from a string value to a hex color value.

Instead, you should parse the String value into its individual components, convert them to integers, and then use the three-argument color() function to create a color.

See this question for more info: Hexadecimal to Integer in Java

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
0

What I did was simply recreated the color like this:

int c = Integer.parseInt(obj.getString("color"), 16);
c = color(red(c), green(c), blue(c));
Tessa Painter
  • 2,113
  • 2
  • 16
  • 21
0

You can try using the following -

Color c = Color.parseColor("#c0c0c0");
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
mileusna
  • 624
  • 6
  • 11
0

int c = -16777216 + unhex("FF0000");

micycle
  • 3,328
  • 14
  • 33