简体   繁体   English

如何在Java中将字符串转换为8位ASCII?

[英]How to convert a string into 8-bit ascii in java?

I want to convert a string text into 8-bit ascii numbers, and try to store them in an ArrayList. 我想将字符串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);
}

But the output for abc is like 但是abc的输出就像

[1100001,1100010,1100011]

Is there any way to make it like 有什么办法让它像

[01100001,01100010,01100011]

Try this complete solution to fix the problem. 尝试使用此完整的解决方案来解决此问题。

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 + "  ");
    }
}

The output is 输出是

[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    
    String in = "abc";
    List<Integer> ascii = new ArrayList<>();

    for (char c : in.toCharArray()) {
        ascii.add((int) c);
        String intString = String.format("%08d", Integer.parseInt(Integer.toBinaryString((int) c)));
        System.out.println(intString);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM