【发布时间】:2013-04-17 23:29:54
【问题描述】:
我有一个生成以下内容的 json 响应:
ledColor : "0xff00ff00" -> 这代表绿色。
我如何在 java/android 中实现以下功能。
将包含"0xff00ff00" 的字符串转换为包含0xff00ff00 的int
提前致谢。
【问题讨论】:
我有一个生成以下内容的 json 响应:
ledColor : "0xff00ff00" -> 这代表绿色。
我如何在 java/android 中实现以下功能。
将包含"0xff00ff00" 的字符串转换为包含0xff00ff00 的int
提前致谢。
【问题讨论】:
根据预期结果的大小使用Long.decode 或Integer.decode 函数。
【讨论】:
使用Long.decode,然后转换为int:
long foo = Long.decode("0xff00ff00");
int bar = (int)foo;
System.out.println("As int: " + bar);
【讨论】:
要获取十六进制字符串的 int 值,请使用 Integer.decode。
例如:
int val = Long.decode("0xff00ff00").intValue();
System.out.println(val);
打印出 -16711936。
【讨论】:
请注意 - 请注意,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,所以我可能完全错了!
【讨论】: