I've searched everywhere, but i couldn't find a suiting solution.
I have a RGB color that i want to convert to this format: 0xffffffff
Many answers convert it to this format: #ffffff
Does anyone know how to convert it to this format (0xffffffff
)?
EDIT: Solved! I actually needed a int but i accidentally said string, woopsie. Seems to work now, thanks!
Snippet:
double frequency = .3;
double r = 255;
double g = 255;
double b = 255;
for (int i = 0; i < 32; ++i)
{
// I am trying to make a rainbow, hence this for loop and the Math.sin
r = Math.sin(frequency*i + 0) * 127 + 128;
g = Math.sin(frequency*i + 2) * 127 + 128;
b = Math.sin(frequency*i + 4) * 127 + 128;
int red = (int)r;
int green = (int)g;
int blue = (int)b;
// converting, outputs a string
System.out.println(result);
}
In case you want the number not as an string
, but as an int
:
0xRRGGBB
RR
, GG
, BB
each represent a value between 0 - 255 (the RGB-values). Each digit of the hex-number can have values ranging from 0 - 16, means that you will need to store numbers up to 16 ^ 6 = 16.777.216
-> dataype int
should be ok.
Then simply make your int
:
int hexval = red * 65536 + green * 256 + blue;
System.out.printf("0x%06X\n", hexval);
public class Main {
public static void main(String[] args) {
double frequency = .3;
int red = (int) (Math.sin(frequency * 10 + 0) * 127 + 128);
int green = (int) (Math.sin(frequency * 10 + 2) * 127 + 128);
int blue = (int) (Math.sin(frequency * 10 + 4) * 127 + 128);
int result = Integer.parseInt(String.format("%02x%02x%02x", red, green, blue), 16);
System.out.println("Decimal representation: " + result);
System.out.println("Hexdecimal representation: " + String.format("0x%06x", result));
}
}
Output:
Decimal representation: 9504467
Hexdecimal representation: 0x9106d3
public static int colorToInt(int r, int g, int b) {
int result = 0;
result += r;
result = result << 8;
result += g;
result = result << 8;
result += b;
return result;
}
Here's an example:
System.out.println(0xffffff); // 16777215
System.out.println(colorToInt(255, 255, 255)); // 16777215
Repl: https://repl.it/repls/IrritatingTwinConsulting.
This function accepts int, instead of double, but I don't think it's a problem. Hope I understood your question correctly.
User contributions licensed under CC BY-SA 3.0