Take the Binary From Text Area and then Converting to Hexa - java

I want to take a binary in the text area and convert it to hex. When calculated using the calculator, result is "E0AC882AA428B6B8", but with my code result is "30".
String str = txtXOR.getText();
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
int x = chars.length;
for(int i = 0; i < x; i++){
hex.append(Integer.toHexString((int)chars[i]));
txtXORToHexa.setText(Integer.toHexString((int) chars[i]));
}
Could someone point out where I have gone wrong?

You should use Integer#parseInt(String s, int radix) with base 2 to parse the binary string and then use toHexString to get the Hex String:
String binaryStr = txtXOR.getText();
int number = Integer.parseInt(binaryStr, 2);
String hexStr = Integer.toHexString(number);
txtXORToHexa.setText(hexStr);
In case you must support very large number you can use BigInteger:
String binaryStr = txtXOR.getText();
BigInteger number = new BigInteger(binaryStr, 2);
String hexStr = number.toString(16);
txtXORToHexa.setText(hexStr);

Related

Converting selective elements in an array of Strings to their ascii values in java

I'm working on a project currently where I have a String array of 8 values that number but are stored as strings. String[3] and String[7] are letters stored as strings that I need to convert to their ASCII values, but I can't seem to do that in java. I keep getting an error saying that I cannot convert a String type to int type, and I don't know any other way to get these string letters to their ASCII values. Here is the code I have so far...
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = Integer.parseInt(stringInfo[x]);
System.out.println(info[x]);
x++;
}
so within that array, those two values need to be turned into ASCII but that code keeps getting errors and I don't know how to fix it. How would I do this?
The best way to do this would be to first convert your string to a character, and then cast your character as an int. I know this sounds like a lot, but it is actually only one line of code.
int ascii = (int) mystring.charAt(0);
The reason this works is that characters (char) are a primary type in Java, and they essentially are just bit, which is why you can actually compare chars to each other using == rather than .equals.
This is a function that use ascii code to convert string of unsigned number to an integer:
static int stringToNumber(String input) {
int output = 0;
for (int x = 0; x < input.length(); x++) {
output = output * 10 + (input.charAt(x) - '0');
}
return output;
}
And your code
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = stringToNumber(stringInfo[x]);
System.out.println(info[x]);
x++;
}
But if you don't need ascii code or your number are signed number java made it easier you can only use this method to convert string to number
Integer result = Integer.valueOf(stringInfo[x]);
And your code:
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = Integer.valueOf(stringInfo[x]);
System.out.println(info[x]);
x++;
}
You can try-
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = stringInfo.charAt(x);
System.out.println(info[x]);
x++;
}
stringInfo.charAt(i) will give the Ascii value at index(i) of stringInfo

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

Java - Convert a String of letters to an int of corresponding ascii?

I want to convert a String, lets say "abc", to an int with the corresponding ascii: in this example, 979899.
I've run into two problems:
1) what I wrote only works for characters whose ascii is two characters long and
2) since these numbers get very big, I can't use longs and I'm having trouble utilizing BigIntegers.
This is what I have so far:
BigInteger mInt = BigInteger.valueOf(0L);
for (int i = 0; i<mString.length(); i++) {
mInt = mInt.add(BigInteger.valueOf(
(long)(mString.charAt(i)*Math.pow(100,(mString.length()-1-i)))));
}
Any suggestions would be great, thanks!
What's wrong with doing all the concatenation first with a StringBuilder and then creating a BigInteger out of the result? This seems to be much simpler than what you're currently doing.
String str = "abc"; // or anything else
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
you don't have to play the number game. (pow 100 etc). just get the number string, and pass to constructor.
final String s = "abc";
String v = "";
final char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
v += String.valueOf((int) chars[i]);
}
//v = "979899" now
BigInteger bigInt = new BigInteger(v); //BigInteger
BigDecimal bigDec = new BigDecimal(v); // or BigDecimal
To handle n-digit numbers, you will have to multiply by a different power of ten each time. You could do this with a loop:
BigInteger appendDigits(BigInteger total, int n) {
for (int i = n; i > 0; i /= 10)
total = total.multiply(10);
return total.plus(new BigInteger(n));
}
However, this problem really seems to be about manipulating strings. What I would probably do is simply accumulate the digits int a string, and create a BI from the String at the end:
StringBuilder result = new StringBuilder();
for (char c : mString.getBytes())
result.append(String.valueOf(c));
return new BigInteger(result.toString());

Convert an integer to an array of characters : java

What is the best way to convert an integer into a character array?
Input: 1234
Output: {1,2,3,4}
Keeping in mind the vastness of Java language what will be the best and most efficient way of doing it?
int i = 1234;
char[] chars = ("" + i).toCharArray();
You could try something like:
String.valueOf(1234).toCharArray();
Try this...
int value = 1234;
char [] chars = String.valueOf(value).toCharArray();
You can convert that integer to string and then convert that string to char arary:-
int i = 1234;
String s = Integer.toString(i);
Char ch[] = s.toCharArray();
/*ch[0]=1,ch[1]=2,ch[2]=3,ch[3]=4*/
This will convert an int to a 2 char array. If you are trying to get the minimum amount of chars, try this.
//convert int to char array
int valIn = 111112222;
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.putInt(valIn);
char [] charArr = new char[4];
charArr[0] = bb1.getChar(0);
charArr[1] = bb1.getChar(2);
//convert char array to int
ByteBuffer bb2 = ByteBuffer.allocate(8);
bb2.putChar(0,charArr[0]);
bb2.putChar(2,charArr[1]);
long valOut = bb2.getInt(0);
I was asked this question in google interview. If asked in interviews use module and division. Here is the answer
List<Integer> digits = new ArrayList<>();
//main logic using devide and module
for (; num != 0; num /= 10)
digits.add(num % 10);
//declare an array
int[] arr = new int[digits.size()];
//fill in the array
for(int i = 0; i < digits.size(); i++) {
arr[i] = digits.get(i);
}
//reverse it.
ArrayUtils.reverse(arr);
Say that you have an array of ints and another method that converts those ints to letters, like for a program changing number grades to letter grades, you would do...
public char[] allGradesToLetters()
{
char[] array = new char[grades.length];
for(int i = 0; i < grades.length; i++)
{
array[i] = getLetter(grades[i]);
}
return array;
}

Categories