如何将字符串转换为位(而不是字节)或位数组,在Java中进行一些操作,如何转换为整数数组(每32位转换为整数,然后将其放入数组中?我从未在Java中进行过这种转换。
String->array of bits->(some operations I'll handle them)->array of ints
如何将字符串转换为位(而不是字节)或位数组,在Java中进行一些操作,如何转换为整数数组(每32位转换为整数,然后将其放入数组中?我从未在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);
THIS IS THE ANSWER
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);
s.toCharArray()
,其中s
是一个String
变量。byte a[]=new byte[160];
String s="abc";
a=s.getBytes();
for(int i=0;i<s.length();i++)
{
System.out.print(a[i]+" ");
}
可能是这样(我当前的电脑没有编译器,无法测试是否可行,但它可能会对您有所帮助):
String st="this is a string";
byte[] bytes=st.getBytes();
List<Integer> ints=new ArrayList<Integer>();
ints.addAll(bytes);
如果编译器失败了
ints.addAll(bytes);
你可以用它来替换
for (int i=0;i<bytes.length();i++){
ints.add(bytes[i]);
}
如果你想要精确获取数组:
ints.toArray();
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+" ");
}