gpt4 book ai didi

java - java中如何将字符串转换为8位ascii?

转载 作者:行者123 更新时间:2023-11-30 07:46:28 26 4
gpt4 key购买 nike

我想将字符串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

关于java - java中如何将字符串转换为8位ascii?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33864306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com