我想得到一个字符串的前两个字节。例如"你好"二进制是:
01101000 01101001 00100000 01110100 01101000 01100101 01110010 01100101
我想要二进制的前两个字节,在这种情况下是01101000 01101001
。
答案 0 :(得分:0)
基本方法。转换为字节数组,然后获取所需的字符,然后根据需要进行格式化。
public class Main {
public static void main(String[] args) {
StringBuilder result = getBinary("hi there", 2);
System.out.println(result.toString());
}
public static StringBuilder getBinary(String str, int numberOfCharactersWanted) {
StringBuilder result = new StringBuilder();
byte[] byt = str.getBytes();
for (int i = 0; i < numberOfCharactersWanted; i++) {
result.append(String.format("%8s", Integer.toBinaryString(byt[i])).replace(' ', '0')).append(' ');
}
return result;
}
}
答案 1 :(得分:-1)
此函数接受输入字符串和要转换为位的字节数。 像这样称呼它: getBits(“hi there”,2)
public String getBits(String str, int count) {
String out = ""; //output string
byte[] content = str.getBytes(); //get the bytes from the input string to convert each byte to bits later
for(int k=0;k!=count;k++) { //go through the bytes
String binary = Integer.toBinaryString(content[k]); //convert byte to a bit string
if(binary.length()<8) { //toBinaryString just outputs necessary bits so we have to add some
for(int i=0;i<=(8-binary.length());i++) {
binary = "0"+binary; //add 0 at front
}
}
out = out + binary; //add it to the output string
}
return out;
}