Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How to convert string into bits(not bytes) or array of bits in Java(i will do some operations later) and how to convert into array of ints(every 32 bits turn into the int and then put it into the array? I have never done this kind of conversion in Java.

String->array of bits->(some operations I'll handle them)->array of ints
like image 235
Yoda Avatar asked Jul 06 '12 18:07

Yoda


People also ask

Can we convert string to byte array in java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

How do I convert a string to an int array?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

How is a string converted to an int in java?

The method generally used to convert String to Integer in Java is parseInt() of String class.


2 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);
like image 96
Louis Wasserman Avatar answered Nov 01 '22 07:11

Louis Wasserman


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);
like image 27
Yoda Avatar answered Nov 01 '22 08:11

Yoda