How to convert string to bits and then to int array - java

How to convert a string to bits (not bytes) or an array of bits in Java (I will do some operations later) and how to convert an ints to an array (every 32 bits turn into int and then put them into an array "I never did such a conversion in Java .

String->array of bits->(some operations I'll handle them)->array of ints
+5
source share
7 answers
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);
+9
source

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);
+2
source

this:

string.getBytes();

, , , .

0

, , ( , , UNICODE ), s.toCharArray(), s String .

0

"abc" , "abc" ASCII- ( 97 98 99).

byte a[]=new byte[160];
String s="abc";
a=s.getBytes();
for(int i=0;i<s.length();i++)
{
    System.out.print(a[i]+" ");
}
0

( , , ):

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();
0

, , Java char - 16- . '\ u0000' ( 0) '\ uffff' ( 65535 ). char integer, :

    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+" ");
    }
0

All Articles