如何将字符串转换为位然后转换为int数组 – java

如何在Java中将字符串转换为位(不是字节)或位数组(我稍后会做一些操作)以及如何转换为整数数组(每32位变成int然后将它放入数组中?我有从未在Java中进行过这种转换。

String->array of bits->(some operations I'll handle them)->array of ints 

 ByteBuffer bytes = ByteBuffer.wrap(string.getBytes(charset)); // you must specify a charset IntBuffer ints = bytes.asIntBuffer(); int numInts = ints.remaining(); int[] result = new int[numInts]; ints.get(result); 

这是答案

 String s = "foo"; byte[] bytes = s.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(' '); } System.out.println("'" + s + "' to binary: " + binary); 

你正在寻找这个 :

 string.getBytes(); 

不是列表,它是一个数组,但您可以稍后使用它,甚至将其转换为整数。

好吧,也许你可以跳过String to bits转换并直接转换为int数组(如果你想要的是每个字符的UNICODE值),使用s.toCharArray() ,其中s是一个String变量。

这会将“abc”转换为字节,然后代码将在相应的ASCII代码中打印“abc”(即97 98 99)。

 byte a[]=new byte[160]; String s="abc"; a=s.getBytes(); for(int i=0;i 

可能是这样(我当前的计算机中没有编译器,不测试它是否有效,但它可以帮助你一点):

 String st="this is a string"; byte[] bytes=st.getBytes(); List ints=new ArrayList(); ints.addAll(bytes); 

如果编译器失败了

 ints.addAll(bytes); 

你可以用它替换它

 for (int i=0;i 

如果你想得到完全数组:

 ints.toArray(); 

请注意,字符串是一系列字符,在Java中,每个字符数据类型都是一个16位Unicode字符。 它的最小值为’\ u0000’(或0),最大值为’\ uffff’(或65,535(含))。 为了得到char整数值,请执行以下操作:

  String str="test"; String tmp=""; int result[]=new int[str.length()/2+str.length()%2]; int count=0; for(char c:str.toCharArray()) { tmp+=Integer.toBinaryString((int)c); if(tmp.length()==14) { result[count++]=Integer.valueOf(tmp,2); //System.out.println(tmp+":"+result[count-1]); tmp=""; } } for(int i:result) { System.out.print(i+" "); }