How to convert string into bits and then into int array - java - 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

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

You are looking for this:
string.getBytes();
Not list, it's an array but you can use it later on, even to convert it to integers.

Well, maybe you can skip the String to bits conversion and convert directly to an array of ints (if what you want is the UNICODE value of each character), using s.toCharArray() where s is a String variable.

This will convert "abc" to byte and then the code will print "abc" in respective ASCII code (ie. 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]+" ");
}

May be so (I have no compiler in my current computer and don't test if it work, but it can help you a bit):
String st="this is a string";
byte[] bytes=st.getBytes();
List<Integer> ints=new ArrayList<Integer>();
ints.addAll(bytes);
If compiler fails in
ints.addAll(bytes);
you can replace it with
for (int i=0;i<bytes.length();i++){
ints.add(bytes[i]);
}
and if you want to get exactly array:
ints.toArray();

Note that string is a sequence of chars, and in Java each char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In order to get char integer value do this:
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+" ");
}

Related

How to store an integer variable as an input in character array in Java?

Convert aaabbcc string to a string a3b2c2.Here is there any way to store integer value 3 in a character array.Can I convert aaabbcc string into a string a3b2c2.
Integer data type requires 32 bit or 4 bytes space whereas character array contains blocks of 16 bits or 2 bytes space.
You might want to create an another integer array to hold your count values as this is not possible in the same character array directly.
There is a workaround of storing ASCII values of corresponding count values as characters in the same array but it might lead to ambiguity if there are numbers present as part of your original character array.
Hence I would suggest you use a separate integer array.
String str = "aaabbcc";
char c;
ArrayList<String>count=new ArrayList();
for(int i = 0; i < str.length(); i++){
if(!count.contains(str.charAt(i)+"")){
count.add(str.charAt(i)+"");
}
}
int [] dd = new int [count.size()];
for (int i = 0; i < str.length(); i++) {
c=str.charAt(i);
for(int j=0;j<count.size();j++){
if(count.get(j).equals(c+"")){
dd[j]++;
}
}
}
String newS="";
for(int i=0;i<count.size();i++){
newS+=count.get(i)+dd[i];
}
str = newS;
System.out.println(str);
you can do it using String, like you want to store 3 at 2nd position so do like this-
int n = 3;
String s = Integer.toString(n);
ch[1] = s.charAt(0); // ch[1] is representing 2nd position in aaabbc

ArrayStoreException during array byte concatenation

Below is my code to convert a string into its ascii equivalent. The string will contain only numbers - which is why I am allocating 2 byte for each character (since 1 to 9 is 49 to 58 in ascii respectively)
But I am getting a java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method) . Any idea why this is happening? Keep in mind that I will be only putting in numbers as Strings as mentioned before.
public byte[] intToAscii(String assetId) { // class main
int stringLength = assetId.length();
byte[] retBuf = new byte[stringLength];
int offset = 0;
for(int i = 0; i < stringLength ; i++){
char character = assetId.charAt(i);
byte ascii = (byte) character;
System.arraycopy(ascii, 0, retBuf, offset, 1);
offset += 1;
}
return retBuf;
}
The first and third parameter to arraycopy must be arrays, and ascii is a byte, not a byte[].
If you want to convert the string assetId to ASCII bytes, just call getBytes():
public byte[] intToAscii(String assetId) {
return assetId.getBytes(StandardCharsets.US_ASCII); // or getBytes("US-ASCII") if pre-Java 7
}

How to convert a "binary" String literal of 256 chars into a hexadecimal notation?

I have 0 and 1 String type combination with total 256 length.
How can I convert it to hexadecimal?
I can do it with combination for 64 or less length, but cant do the same when the length is 256
could you help me please? Any example?
Many thanks in advance.
Simplest way is to use BigInteger. It's capable to convert String of any length as long as you have enough memory:
String str = "100010110101...";
String hex = new BigInteger(str, 2).toString(16);
It's also not very difficult to implement this conversion without using the intermediate BigInteger just splitting the input string into fixed length chunks (works for arbitrary length input strings as well):
public static String binToHex(String str) {
int l = str.length();
StringBuilder result = new StringBuilder();
int cur = 0;
for (int next = l - l / 32 * 32; next <= l; next += 32) {
result.append(Long.toHexString(Long.parseLong(
str.substring(cur, next), 2)));
cur = next;
}
return result.toString();
}

Java String, single char to hex bytes

I want to convert a string by single char to 5 hex bytes and a byte represent a hex number:
like
String s = "ABOL1";
to
byte[] bytes = {41, 42, 4F, 4C, 01}
I tried following code , but Byte.decode got error when string is too large, like "4F" or "4C". Is there another way to convert it?
String s = "ABOL1";
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
String hex = String.format("%02X", (int) array[i]);
bytes[i] = Byte.decode(hex);
}
Is there any reason you are trying to go through string? Because you could just do this:
bytes[i] = (byte) array[i];
Or even replace all this code with:
byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
You can convert from char to hex String with String.format():
String hex = String.format("%04x", (int) array[i]);
Or threat the char as an int and use:
String hex = Integer.toHexString((int) array[i]);
Use String hex = String.format("0x%02X", (int) array[i]); to specify HexDigits with 0x before the string.
A better solution is convert int into byte directly:
bytes[i] = (byte)array[i];
The Byte.decode() javadoc specifies that hex numbers should be on the form "0x4C". So, to get rid of the exception, try this:
String hex = String.format("0x%02X", (int) array[i]);
There may also be a simpler way to make the conversion, because the String class has a method that converts a string to bytes :
bytes = s.getBytes();
Or, if you want a raw conversion to a byte array:
int i, len = s.length();
byte bytes[] = new byte[len];
String retval = name;
for (i = 0; i < len; i++) {
bytes[i] = (byte) name.charAt(i);
}

I want to be able to convert numbers into text according to the ASCII decimal table

I am trying to make it so that I can take individual three-character substrings and convert them to integers under the conditions tht the length of the String is a multiple of three. The integers into which the partioned substrings are converted are supposed to function as relative positions in an array that contains all the printing characters of the ASCII table.
String IntMessage = result.toString();
if
{
(IntMessage.substring(0,1)=="1" && IntMessage.length()%3==0)
for(j=0;j < IntMessage.length()-2;j += 3)
n = Integer.parseInt(IntMessage.substring(j,j+3));
mess += ASCII[n-32];
return mess;
Under otherwise conditions, the method should take the first two characters of the String and initialize them to a variable i. In this case, the variable mess is initialized to the character in the ASCII array with an index of i-32. Then there is a for loop that takes the remaining characters and partitions them into three-digit substrings and they are taken and changed into strings according to their corresponding positions in the ASCII array. The String variables in this array are continuously added on to the the variable mess in order to get the BigInteger to String conversion of the IntMessage String.
int i = Integer.parseInt(IntMessage.substring(0,2));
mess=ASCII[i-32];
for(l=2; l< IntMessage.length() - 2; l+=3)
r = Integer.parseInt(IntMessage.substring(l,l+3));
mess+=ASCII[r-32];
return mess;
For some reason the method isn't working and I was wondering whether I was doing something wrong. I know how to take an input String and convert it into a series of numbers but I want to do the opposite also. Is there anyway you could help?
Based on your description you can use the following methods:
String fromIntMessage(String msg) {
StringBuilder result = new StringBuilder();
for (int x = (msg.length() % 3 - 3) % 3; x < msg.length(); x += 3) {
int chr = Integer.parseInt(msg.substring(Math.max(x, 0), x + 3));
result.append(Character.toString((char) (chr - 32)));
}
return result.toString();
}
String toIntMessage(String string) {
StringBuilder result = new StringBuilder();
for (char c : string.toCharArray()) {
result.append(String.format("%03d", c + 32));
}
return result.charAt(0) == '0' ? result.substring(1) : result.toString();
}
which will give you
toIntMessage("DAA") // => "100097097"
fromIntMessage("100097097") // => "DAA"

Categories