对于一项作业,我试图将字符串转换为 7 位二进制文件。但是,我们不允许使用 Integer.toBinaryString(int)。这是我到目前为止所拥有的
public static int[] encodeToBit(String str) {
int[] convertString = new int[str.length() * 7];
for (int i = 0; i < convertString.length; i++) {
convertString[i] = (int)str.charAt(i);
for (int j = convertString.length; j >=0 ; j--) {
while (true) {
convertString[i] =
}
}
}
return convertString;
}
有关如何将 char 的整数 ASCII 表示形式转换为 7 位二进制的任何建议。
编辑: 例如,encodeToBit(“C”)应该输出数组
[ 1, 0, 0, 0, 0, 1, 1 ]
最佳答案
我假设您想要一个由 0 和 1 组成的数组,每个字符有 7 个。
public static byte[] encodeTo7Bits(String str) {
byte[] bytes = new byte[str.length() * 7];
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
assert ch < 128;
for (int j = 0; j < 7; j++)
bytes[i * 7 + j] = (byte) ((ch >> (7 - j)) & 1);
}
return bytes;
}
关于java - 如何将字符串转换为7位二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36519977/