我想将字符串text
转换为8位ascii数字,并尝试将它们存储在ArrayList中。
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
int ascii_dec = (int) c;
String ascii_str = Integer.toBinaryString(ascii_dec);
int ascii_bi = Integer.parseInt(ascii_str.toString());
messageList.add(ascii_bi);
}
但是
abc
的输出就像[1100001,1100010,1100011]
有什么办法让它像
[01100001,01100010,01100011]
最佳答案
尝试使用此完整的解决方案来解决此问题。
public static void main(String[] args) {
ArrayList<String> messageList = new ArrayList<String>();
String text = "abc";
byte[] bytes = text.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
messageList.add(binary.toString());
System.out.println(Arrays.toString(bytes));
for (String object : messageList) {
System.out.println("'" + text + "' to binary: " + object);
}
// this part below to help you to save 2-bit binary converted in int
// arraylist to store string
ArrayList<String> stringList = new ArrayList<String>();
for (int i = 0; i < text.length(); i++) {
stringList.add(messageList.get(0).split(" ")[i]);
}
// arraylist to store int converted
ArrayList<Integer> intList = new ArrayList<Integer>();
for (String str : stringList) {
for (int i = 0; i < str.length(); i += 2) {
intList.add(Integer.parseInt(str.substring(i, i + 2), 2));
System.out.print(str.substring(i, i + 2) + " ");
}
}
System.out.println();
// nowretrieve int in arraylist to convert in 2-binary if you wont
for (Integer integer : intList) {
System.out.print(integer + " ");
}
}
输出是
[97, 98, 99]
'abc' to binary: 01100001 01100010 01100011
01 10 00 01 01 10 00 10 01 10 00 11
1 2 0 1 1 2 0 2 1 2 0 3