BigInteger to String according to ASCII - java

Is there a way to convert a series of integers to a String according to the ASCII table. I want to take the ASCII value of a String and convert it back to a String. For example,
97098097=> "aba"
I really need an effective way of taking an integer and converting it to a String according to its ASCII value. This method must also take into account the fact that there is no zero in front of the '9' when the String "aba" has an ASCII value of 97098097 as 'a' has an ASCII value of 097 and a String "dee" has one of 100101101. This means that not every number will have an ASCII value that has a number of digits that is a multiple of three.
If you have any misunderstandings of what I'm trying to do please let me know.

No lookup table required.
while (string.length() % 3 != 0)
{
string = '0' + string;
}
String result = "";
for (int i = 0; i < string.length(); i += 3)
{
result += (char)(Integer.parseInt(string.substring(i, i + 3)));
}

First, I would create some sort of lookup table in your code with all the ascii values and their String equivalent. Then take the big int and convert it to a String. Then do the mod of 3 with the length of your bigint string to determine if you need to add 1, 2, or no 0's to the front of it. Then just grab every 3 integers from the front of the number, compare it to the lookup table, and append the corresponding value to your result string.
Example:
Given 97098097
You would convert it to: "97098097"
Then you do a mod with 3 resulting in a value of 1, so 1 zero needs to be added.
Append 1 zero: "097098097"
Then grab every 3 from the front and compare to look up table:
097 -> a, so result += "a"
098 -> b, so result += "b"
097 -> a, so result += "a"
You end with result being "aba"

Related

Java int value type to Character

I am new to java and and working on a crud calculator that takes input and holds it in an ArrayList to perform the calculations.
I am trying to add two values in an ArrayList<Character> and then replace the "+" with the sum.
if(listEqu.contains('+')) {
while(listEqu.indexOf('+') > -1) {
int plus = listEqu.indexOf('+');
int prev = listEqu.get(plus-1);
int nxt = listEqu.get(plus+1);
Character sum = (char) (nxt + prev);
listEqu.set(plus, sum);
System.out.println(listEqu);
}
}
When the input is 1+1, this returns [1, b, 1].
What I want is to return [1, 2, 1] .
Any advice? Thanks!
The problem is actually that adding two characters doesn't do what you expect.
The value of '1' + '1' is 'b'. If you want the next digit after '1' you add the integer 1 to it; i.e. '1' + 1 is '2'.
For a deeper understanding, you need to understand how character data is represented in Java.
Each char value in Java is an unsigned 16 bit integer that corresponds to a code point (or character code) in the Unicode basic plane. The first 128 of these code points (0 to 127) correspond to a characters in the old ASCII character set. In ASCII the codes that represent digits are 48 (for '0') through to 39 (for '9'). And the lowercase letters are 97 (for 'a') through to 122 (for 'z').
So as you can see, '1' + '1' -> 49 + 49 -> 98 -> 'b'.
(In fact there is a lot more to it than this. Not all char values represent real characters, and some Unicode code-points require two char values. But this is way beyond the scope of your question.)
How could I specify addition of numbers instead of addition of the characters?
You convert the character (digit) to a number, perform the arithmetic, and convert the result back to a character.
Read the javadoc for the Character class; e.g. the methods Character.digit and Character.forDigit.
Note that this only works while the numbers remain in the range 0 through 9. For a number outside of that range, the character representation consists of two or more characters. For those you should be using String rather than char. (A String also copes with the 1 digit case too ...)
Few things that can be improved with your code :
Converting the characters 1 into equivalent integer value:
int prev = Integer.parseInt(String.valueOf(listEqu.get(plus-1)));
int nxt = Integer.parseInt(String.valueOf(listEqu.get(plus+1)));
// Note : int prev = listEqu.get(plus-1) would store an ascii value of `1` to prev value i.e 49
And then converting the sum of those two values into Character back to be added to the list using Character.forDigit as:
Character sum = Character.forDigit(nxt+prev,10);
// Note Character sum = (char) (nxt + prev); is inconvertible
// and char sum = (char) (nxt + prev); would store character with ascii value 98(49+49) in your case 'b' to sum
you should first convert your prevand nxt to int value and then add them together like follow:
if(listEqu.contains('+')) {
while(listEqu.indexOf('+') > -1) {
int plus = listEqu.indexOf('+');
int prev = Integer.parseInt(listEqu.get(plus-1));
int nxt = Integer.parseInt(listEqu.get(plus+1));
Character sum = (char) (nxt + prev);
listEqu.set(plus, sum);
System.out.println(listEqu);
}
}
nxt and prev are char values. Tey take their value in the ASCII table, where '1' is 61 and 'b' is 142 (thus, '1' + '1' = 'b')
You need to substract '0' to get the number they represent. ('1' - '0' = 61 - 60 = 1)
The sum is not necessarily writable with one character, so you shouldn't put it back into a char array.
If you want to convert an integer to a string, use Integer.toString(i).
(And, if you want to, get the first character of the string and put it in the array, if that's what you want)
You need to parse the characters to their corresponding decimal value before you perform the addition, and then back to a character after. The methods Character.digit(char, int) and Character.forDigit(int, int) can do that (and I would use char since that is the type of prev and nxt). Like,
char prev = listEqu.get(plus - 1);
char nxt = listEqu.get(plus + 1);
Character sum = Character.forDigit(Character.digit(nxt, 10)
+ Character.digit(prev, 10), 10);

Getting ints array instead of characters array

I am trying a code problem to convert double to string and then insert that to an array. I tried various methods but these don't give expected output.
public int[] makePi() {
double PI = Math.PI;
String sPI = String.valueOf(PI);
int[] Arr = new int[3];
for(int i =0; i<3; i++)
{
Arr[i] = sPI.charAt(i);
}
return Arr;
}
Output should be an array with first three characters of PI as below :-
[ 3, 1, 4 ] while I am getting [51, 46, 49]
I will handle decimal character if needed.
Just a hint is needed.
Please don't provide full program that will be a spoiler. :-)
Look at the ASCII table. Do you see what are the corresponding chars for the integers you're getting? This should be a good hint for you.
Note that you're assigning the result to an int array, while you're running on characters.
you're storing chars into an int array. hence theie respective ascii values will be stored in array (you're effectively converting char to int)
3 (char) -> 51 (ASCII Value)
. (char) -> 46 (ASCII Value)
1 (char) -> 49 (ASCII Value)
your array length is 3, so only first 3 chars are converted to ascii which is 3.1, not 3.14
But now if you want to store it into an char array (which i feel you're trying to do), all you need is -
char[] charArray = sPI.toCharArray();
Plus, I dont think you want to store in int array as though you can convert ascii values int their respective int value, but what about '.' which is not a valid int.
What you get in your array are values of characters (so something like 70 for '3', I neither remember nor want to remember exact values). You must convert value of character into the number itself. Hint: characters are numbered in the following way:
'0' - n
'1' - n + 1
'2' - n + 2
and so on.
If you want to extract the numeric values of the digits, I would advise against doing explicit comparisons and arithmetic on the character values.
The Character class provides helper methods, which are less error-prone and more readable:
int outIndex = 0;
for (int i = 0; i < 3 /* && i < sPI.length() */; ++i) {
char c = sPI.charAt(i);
if (Character.isDigit(c)) {
Arr[outIndex++] = Character.getNumericValue(c);
}
}
/* assert outIndex == 3 */
return Arr;
I've commented out some code which I'd put in there for more robustness - it's not strictly necessary in this case, since we know that sPI has at least 3 digits in it. (Mind you, if we're going to hard-code that assumption, we may as well simply return new int[] { 3, 1, 4 };).

Java - Converting from unicode to a string?

I can easily create a unicode character and print it with the following lines of code
String uniChar = Character.toString((char)0000);
System.out.println(uniChar);
However, now I want to retrieve the number above, add 3, and print out the new unicode character that the numbers 0003 corresponds to. Is there a way for me to retrieve the ACTUAL string of unichar? As in "\u0000"? That way I could substring just the "0000", convert it to an int, add 3, and reverse the entire process.
I think you're looking for String#codePointAt:
Returns the character (Unicode code point) at the specified index. The index refers to char values (Unicode code units) and ranges from 0 to length()- 1.
If the char value specified at the given index is in the high-surrogate range, the following index is less than the length of this String, and the char value at the following index is in the low-surrogate range, then the supplementary code point corresponding to this surrogate pair is returned. Otherwise, the char value at the given index is returned.
For instance (live copy):
// String containing smiling face with smiling eyes emoji
String str = "😊";
// Get the code point
int cp = str.codePointAt(0);
// Show it
System.out.println(str + ", code point = U+" + toHex(cp));
// Increase it
++cp;
// Get the updated string (from an array of code points)
String updated = new String(new int[] { cp }, 0, 1);
// Show it
System.out.println(updated + ", code point = U+" + toHex(cp));
(toHex is just return Integer.toString(n, 16).toUpperCase();)
That outputs:
😊, code point = U+1F60A
😋, code point = U+1F60B
This code will work in both cases, for codepoints from Unicode BMP and from Unicode supplemental panes which uses 4 bytes in UTF-8 to encode a character. 4 byte code point requires 2 Java char entities to be stored, so in this case string.length() = 2.
// array will contain one or two characters
char[] chars = Character.toChars(codePoint);
// string.length will be 1 or 2
String str = new String(chars);
Unicode is a numbering of "characters" - code points - upto a 3-byte int range.
The UTF-16 encoding uses a sequance of byte pairs, and a java char is such a byte pair. The (int) cast of a char is imperfect and covers only a part of the Unicode. The correct way to convert a code point to possibly more than one char:
int codePoint = 0x263B;
char[] chars = Character.chars(codePoint);
To work with Unicode code points, one can do:
int[] codePoints = {0x2639, 0x263a, 0x263b};
String s = new String(codePoints, 0, codePoints.length);
codePoints[0} += 2;
You code use an int array of 1 code point.
In java 8 one can get an IntStream of code points:
s.codePoints().forEach(cp -> {
System.out.printf("U+%X = %s%n", cp, Character.getName(cp));
};

How to convert a String in java with 1s and 0s to corresponding ASCII value?

How do one convert a String in java with 1 and 0s to corresponding ASCII value?
Lets say I have
String str = "01101110";
How do I convert it to be its corresponding 'n' so I can print n?
System.out.printl(str.toCorrespondingAscii());//output n
int value = Integer.parseInt("01101110", 2); //2 for binary
System.out.println(value); // To print ascii
char digit = (char) value;
System.out.println(digit); // To print n

Convert binary string to ascii text?

I was wondering if it is possible to enter in binary numbers and have them translated back into text. For example I would enter "01101000 01100101 01101100 01101100 01101111" and it would covert it into the word "hello".
Just some logical corrections:
There are three steps here
Turning the binary set into an integer
Then the integer into a character
Then concatenate to the string you're building
Luckily parseInt takes a radix argument for the base. So, once you either chop the string up into (presumably) an array of strings of length 8, or access the necessary substring, all you need to do is (char)Integer.parseInt(s, 2) and concatenate.
String s2 = "";
char nextChar;
for(int i = 0; i <= s.length()-8; i += 9) //this is a little tricky. we want [0, 7], [9, 16], etc (increment index by 9 if bytes are space-delimited)
{
nextChar = (char)Integer.parseInt(s.substring(i, i+8), 2);
s2 += nextChar;
}
See the answer to this question: binary-to-text-in-java.

Categories