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
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.
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.
The method generally used to convert String to Integer in Java is parseInt() of String class.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With