1. Principle
The main methods are called toHexString (converting the int type into a hex string) and parseInt (parsing the string into an int).
2. Code
public static void main(String[] args) { String hexString = colorToHexValue(Color.RED); System.out.println("HexString:" + hexString); Color color = fromStrToARGB(hexString); System.out.println("The ARGB value of the hexString converted to color:("+String.valueOf(color.getAlpha())+","+String.valueOf(color.getRed())+"," +String.valueOf(color.getGreen())+","+String.valueOf(color.getBlue())+")"); } private static String colorToHexValue(Color color) { return intToHexValue(color.getAlpha())) + intToHexValue(color.getRed()) + intToHexValue(color.getGreen())) + intToHexValue(color.getBlue()); } private static String intToHexValue(int number) { String result = Integer.toHexString(number & 0xff); while (result.length() < 2) { result = "0" + result; } return result.toUpperCase(); } private static Color fromStrToARGB(String str) { String str1 = str.substring(0, 2); String str2 = str.substring(2, 4); String str3 = str.substring(4, 6); String str4 = str.substring(6, 8); int alpha = Integer.parseInt(str1, 16); int red = Integer.parseInt(str2, 16); int green = Integer.parseInt(str3, 16); int blue = Integer.parseInt(str4, 16); Color color = new Color(red, green, blue, alpha); return color; }3. Effect
4. Key points
4.1 toHexString: There is nothing to say, JDK provides converting integers into hexadecimal strings.
4.2 number & 0xff : Make sure that only the last 8 bits of int type data are valid, and the higher 24 bits are invalid (all 0), the int type is 32 bits, but the maximum color value is 255, and only 8 bits are needed to meet the needs. Therefore, we must ensure that the incoming data is a legal color value, and data greater than 255 must be treated as 255. At this time, there are two ways. The first is the processing method in this article, and the second is to add judgment. If the data is greater than 255, it is equal to 255, and if it is less, it will not be processed. In comparison, the processing method in this paper is the processing method with the least code and is efficient.
4.3 &: Bitwise "AND" operation. If the binary code is both 1, the result is 1, otherwise it is 0.
4.4 0xff: 0x means that the hexadecimal number is followed by it; f is 15, and when converted to 2, it is 1111, and the two fs are 1111 1111 (255 in decimal), the first 24 bits are 0. At this time, performing the operation ensures that only the int value in the range 0-255 is the valid color value.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.