java有什么api可以将字符串直接转换成相应二进制数

2024-12-21 00:12:56
推荐回答(2个)
回答1:

public class Test01 {
public static void main(String[] args) {

//比如我现在要转这个字符串
String str = "Hello World";

//先把他变为字符数组
char[] chs = str.toCharArray();

//然后通过integer中的toBinaryString方法来一个一个转

for (int i = 0; i < chs.length; i++) {
System.out.print(Integer.toBinaryString(chs[i]));
}

}
}

1001000110010111011001101100110111110000010101111101111111001011011001100100

回答2:

String s = "你好";
字符串转二进制数组

byte[] bys = s.getBytes("UTF-8");
System.out.println(Arrays.toString(bys));

二进制转回字符串
String ss = new String(bys, "UTF-8");
System.out.println(ss);