【发布时间】:2018-02-09 07:05:48
【问题描述】:
我正在使用 Java 中的转换器将 ASCII 值转换为 RGB。当我尝试截断十六进制数据时,会出现我的具体问题。基本上,我想创建一个循环遍历数据的系统,将其转换为 6 位块,并将其添加到数组中。在为额外数据创建单独的字符串时。这是我的代码:
package converter;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
public class ASCIItoRGB{
public static void main(String args[]) {
// Input
String asciiValue = "2121876";
char[] c = asciiValue.toCharArray();
StringBuffer hexValue = new StringBuffer();
for(int i=0; i<c.length; i++) {
hexValue.append(Integer.toHexString((int)c[i]));
}
String hexString = hexValue.toString();
String hexTruncated = hexValue.toString();
ArrayList rgbValues = new ArrayList();
for(int i=0; i<hexString.length(); i++) {
if(hexTruncated.length() >= 6) {
String tempval = hexTruncated.substring(0, 5);
rgbValues.add(Color.decode(tempval));
tempval = hexTruncated.substring(tempval.length(), 5);
}
else {
}
}
// Output
System.out.println("ASCII VALUE: " + asciiValue);
System.out.println("CHAR ARRAY: " + Arrays.toString(c));
System.out.println("HEX VALUE: " + hexString);
System.out.println("RGB VALUES: " + rgbValues.toString());
}
}
【问题讨论】:
-
主要问题是您将字符串的其余部分分配给
tempval而不是hexTruncated。但是整个第二个 for 循环是狡猾的。再想一想。 -
好的,我再试一次。
-
好的。我通过使用 while 循环而不是 for 循环让它工作。
标签: java string loops hex truncate