来自颜色字符串的Java int hex

时间:2013-04-24 12:05:32

标签: java hex

我有一个json响应产生以下内容:

ledColor:"0xff00ff00" - >这代表绿色。

如何在java / android中实现以下功能。

将包含"0xff00ff00"的字符串设置为包含0xff00ff00

的int

提前致谢。

4 个答案:

答案 0 :(得分:3)

要获取十六进制字符串的int值,请使用Integer.decode

例如:

int val = Long.decode("0xff00ff00").intValue();
System.out.println(val);

打印出-16711936。

答案 1 :(得分:2)

使用Long.decodeInteger.decode函数,具体取决于预期结果的大小。

答案 2 :(得分:2)

使用Long.decode然后转换为int:

    long foo = Long.decode("0xff00ff00");
    int bar = (int)foo;
    System.out.println("As int: " + bar);

答案 3 :(得分:1)

小心 - 请注意,Android API似乎“忽略”Java没有明确支持“无符号”整数的概念。

您可能需要查看以下链接:

我在这里制作了一个非常简单的演示应用程序,在某种程度上解释了它。希望能帮助到你! (使用风险自负!)

package com.test;

public class AgbUtil {

    public static int argbFromString(String argbAsString) throws Exception {

        if (argbAsString == null || argbAsString.length() < 10)
            throw new Exception("ARGB string invalid");

        String a =  argbAsString.substring(2, 4);
        String r =  argbAsString.substring(4, 6);
        String g =  argbAsString.substring(6, 8);
        String b =  argbAsString.substring(8, 10);

        System.out.println("aStr: " + a + " rStr: " + r + " gStr: " + g + " bStr: " + b);

        int aInt = Integer.valueOf(a, 16);
        int rInt = Integer.valueOf(r, 16);
        int gInt = Integer.valueOf(g, 16);
        int bInt = Integer.valueOf(b, 16);

        System.out.println("aInt: " + aInt + " rInt: " + rInt + " gInt: " + gInt + " bInt: " + bInt);

        // This is a cheat because int can't actually handle this size in Java - it overflows to a negative number
        // But I think it will work according to this: http://www.developer.nokia.com/Community/Discussion/showthread.php?72588-How-to-create-a-hexidecimal-ARGB-colorvalue-from-R-G-B-values
        // And according to this: http://www.javamex.com/java_equivalents/unsigned.shtml
        return (aInt << 24) + (rInt << 16) + (gInt << 8) + bInt; 
    }

    public static void main(String[] args) {
        System.out.println("Testing");
        try {
        System.out.println("0xff00ff00: " + argbFromString("0xFF00ff00")); // Green
        System.out.println("0xffff0000: " + argbFromString("0xffff0000")); // Red
        System.out.println("0xff0000ff: " + argbFromString("0xff0000ff")); // Blue
        System.out.println("0xffffffff: " + argbFromString("0xffffffff")); // White
        System.out.println("0xff000000: " + argbFromString("0xff000000")); // Black
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我不知道Android,所以我在这里完全错了!!