![](/img/trans.png)
[英]how can I write a function string replace (char a , char b, string s) that replace each occurrence of the character a in the string s by b
[英]How to convert an array of (00s…11s), the binary representation of each character, to a string of char
如何將每個字符的二進制表示形式的(00s ... 11s)數組轉換為char字符串? 在我的代碼中,我取長度為64的int數組,然后將數組除以多次,每次取8個等於8位的索引,然后從長度為8的數組的索引7開始,然后將索引的值乘以( 2 ^索引號,第一次應為7,然后是6.等)
但我收到一個例外。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at testing.cipherText(testing.java:30)
at testing.main(testing.java:8)
如果我的算法不正確,請告訴我
import java.util.*;
public class testing {
public static void main(String [] args)
{
int [] array ={0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1};
String c = cipherText (array);
//System.out.print(i);
}
public static String cipherText (int [] array)
{
int decimal = 0;
int [] intA = new int [8];
int from = array.length;
char x = 0;
int dre;
String s = null;
for (int i = 0; i < array.length; i = i + 8)
{
from=from-8;
intA=copyPartOfArray(array,from,8);
for (int j=0;j<intA.length;j++)
{
dre = (int) Math.pow (2.0, (double)7-i);
dre = dre * intA[i];
decimal = decimal+dre;
x =(char)decimal;
}
s=x+s;
}
return s;
}
public static int [] copyPartOfArray (int [] a, int from, int to) // return a subArray
{
int [] result=new int [to];
System.arraycopy(a,from, result, 0, to);
return result;
}
}
無需創建新數組:
public static String cipherText(int[] array) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < array.length / 8; i++) {
byte dec = 0;
for (int j = 0; j < 8; j++) {
int pow = 1 << 7 - j; // == Math.pow(2, 7 - j)
dec += array[i * 8 + j] * pow;
}
s.append((char) dec);
}
return s.toString();
}
好的,你說的是你的問題
dre = (int) Math.pow(2.0, (double) 7 - i);
dre=dre*intA[i];
我想你想要的
dre = (int) Math.pow(2.0, (double) 7 - j);
dre=dre*intA[j];
你也應該把你的字符串搞砸了
String s = "";
代替
String s = null;
您期望從陣列輸出什么輸出。 還要記住,java中的字符是16位unicode。
盡管如此,我認為你的算法還沒有運行......會繼續尋找
你可能想與...比較
public static String cipherText(int[] array) {
byte[] bytes = new byte[array.length / 8];
for (int i = 0; i < array.length; i += 8)
bytes[i / 8] = (byte) ((array[i] << 7) + (array[i + 1] << 6) + (array[i + 2] << 5) + (array[i + 3] << 4)
+ (array[i + 4] << 3) + (array[i + 5] << 2) + (array[i + 6] << 1) + array[i]);
return new String(bytes, 0);
}
不使用pow
或<<
,只需標准parseByte
:
int [] array={0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1,
0,1,0,1,1,0,0,1};
StringBuilder buffer = new StringBuilder();
assert array.length % 8 == 0;
for(int current:array) {
buffer.append(current);
}
int steps = array.length/8;
byte [] letters = new byte[steps];
for(int i=0; i<steps; i++) {
letters[i] = Byte.parseByte(buffer.substring(i*8, i*8+8), 2);
}
String result = new String(letters);
System.err.println(result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.