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?

4
  • 1
    how do I do this? do what? Commented Feb 14, 2018 at 1:03
  • convert a hex string to a usable color or an int of that color's value Commented Feb 14, 2018 at 1:09
  • Use the available constructors? docs.oracle.com/javase/7/docs/api/java/awt/… Commented Feb 14, 2018 at 1:10
  • It's done well apparently what you want to do. Commented Feb 14, 2018 at 1:19

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

3 Comments

Please note the processing tag. Processing is its own language, and you should not use Java's AWT Color type inside Processing. Recommended reading: Processing != Java
Given the java tag it's an easy mistake to make.
I didn't say otherwise.
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

Comments

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

Comments

0

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

Comments

-1

You can try using the following -

Color c = Color.parseColor("#c0c0c0");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.