To convert a hexadecimal color value to an RGB color value in Java, you can use the Integer.valueOf
method to parse the hexadecimal string and then use bit shifting and masking to extract the individual red, green, and blue color components.
Here is an example of how to convert a hexadecimal color value to an RGB color value:
refer to:lautturi.compublic class HexToRGB { public static void main(String[] args) { String hex = "#FF0000"; // red int rgb = Integer.valueOf(hex.substring(1), 16); int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; System.out.println("r = " + r + ", g = " + g + ", b = " + b); } }
In this example, the hex
variable is a string containing a hexadecimal color value. The Integer.valueOf
method is used to parse the hexadecimal string and convert it to an integer. The substring
method is used to remove the leading "#" character from the hexadecimal string.
The individual red, green, and blue color components are extracted from the integer value using bit shifting and masking. The red component is obtained by shifting the integer value 16 bits to the right and then masking the lower 8 bits with the value 0xFF. The green component is obtained by shifting the integer value 8 bits to the right and then masking the lower 8 bits with the value 0xFF. The blue component is obtained by masking the lower 8 bits of the integer value with the value 0xFF.
The extracted color components are then printed to the console using the println
method of the System.out
object.
This example will output the following to the console:
r = 255, g = 0, b = 0
Which represents the red, green, and blue color components of the hexadecimal color value "#FF0000".