I am trying to reform a string from ascii characters. I noticed when I break down ascii it matches the number with the ascii char, this changes when I tried to do (c+=c+0) on it as seen below, I tried to revert back to the original string but it doesn't seems to work. I was wondering does the ascii number change when you append it to a string?
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); //'e'
System.out.println(c+0); //101 -ascii
b.append(c+=c+0);
char d = b.charAt(0);
System.out.println(d-=d+0); //blank
When you use + to sum a char with and int, the result will be promoted
to int.
When you use compound assignment operators +=, the result will be converted to left
operand data type(in this case, char)
This is what happens with your code:
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); //'e'
System.out.println(c+0); //101 -ascii
b.append(c+=c+0); // result of c+c+0 is int 202, it is converted to char Ê
char d = b.charAt(0); // char d = Ê
System.out.println(d-=d+0); // result of d-(d+0) is int 0, it will be converted to null
It's not clear what you're trying to accomplish, but hopefully this example helps you figure out what's going on:
public static void main(String[] args) {
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); // e
System.out.println((int) c); // 101
char doubleC = (char) (c + c);
b.append(doubleC);
char d = b.charAt(0);
System.out.println((int) d); // 202
System.out.println(d - c); // 101
System.out.println((char) (d - c)); // e
}
Whether a character is printed as a letter or its ASCII value depends on its type. You can see that (int) c casts the character to its int ASCII value. Your approach of c+0 also does this but in a less intuitive way.
You also apparently want to "undo" your modification to c, but subtracting d-d always gives you 0. You need to store your value of c and subtract that from d.
+0s don't do anything because the character is underneath a number (so it's essentially like saying 101 + 0).
d-=d+0 evaluates to d = d - d + 0, so (because we're manipulating chars) d - d = 0
If you wanted to get c from d, you'd have to do d = d - c, because 'c' is the difference between the initial and the final value.
So no, the ASCII number of a character doesn't change, you're just not doing the reverse calculation as you should be.
It's like saying: x + y = z,
and then wondering why z - z != y.
You should be doing: z - x = y
#Edit
To add to your comment under pkpnd's answer - if you have only String b to work with, you'd still need to know the difference (i.e. by how much you increased/decreased the number) to reverse to the original chars.
Related
I have a simple block of code, can someone explain to me why this acceptable in Java?
int a = 10;
int c = 'A' + (a -1);
System.out.println(c);
The result of this displayed in compiler is: 74.
So where exactly the values of seventies come from?
Thanks for your answers.
In Java a char can be (explicitly or implicitly) casted to int, it then uses the ASCII value associated to this character.
It your case, the seventies comes from the character 'A'. The ASCII value of this character is 65. So the system implicitly does the casting 'A' → 65. Your calculation does:
c = 'A' + (a-1)
↓
c = 65 + (10-1)
↓
c = 74
The ascii value of 'A' is 65. Check this link for complete reference. The conversion occurs through (implicit) widening the char datatype to int datatype using its unicode value, which in this case for 'A' is 65 (jls 5.6.1).
Char is implicitly converted into integer resulting 'A' = 65
so 65+9 = 74
When you assign value of one data type to another, the two types might not be compatible with each other. It should be casted to correct type:
There are 2 types:-
Widening or Automatic Type Conversion.
which casts in this sequence:
byte -> short -> int -> long -> float -> double
char -> int
example :
int i = 100; //i is 100
float f = i; // f is 100.0
Narrowing or Explicit
Conversion. which casts in this sequence:
double -> float -> long -> int ->short -> byte
example:
double d = 100.100; //d is 100.100
int i = (int)d; //i is 100
So, When a Character value is used in integer context. It is automatically casted to int.
In your case:
int a = 10;
int c = 'A' + (a -1); //c = 65 + (10-1)
'A' ascii value is 65, thus you get c = 74
Hope this helps.
I understand how to convert a single char to an int, but how can I convert a String to chars, so I can convert the chars to ints? For example, for the string hello:
chars[1] = h => 104
chars[2] = e => 101
chars[3] = l => 108
chars[4] = l => 108
chars[5] = o => 111
The output should make it easy to convert five-letter Strings to five separate integers, each representing one character, then convert them back to char and print them as a single String again.
You can try like this:
String s = "hello";
char[] data = s.toCharArray(); // returns a length 5 char array ( 'h','e','l','l','o' )
Now you can call this function to convert it into int.
int charToInt(char []data,int start,int end) throws NumberFormatException
{
int result = 0;
for (int i = start; i < end; i++)
{
int digit = (int)data[i] - (int)'0';
if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
result *= 10;
result += digit;
}
return result;
}
Using getBytes(), you can get a byte[] containing an number representation of each letter in the String:
byte[] text = "hello".getBytes();
for(byte b : text) {
System.out.println(b);
}
This gives the same results as:
String text = "hello";
for(char c : text.toCharArray()) {
System.out.println((int) c);
}
This is the easiest way I can possibly think of to achieve this goal. To convert it back to String:
byte[] byteArray = "hello".getBytes();
String string = new String(byteArray);
You can pass the given string in the constructor parameter of StringBuilder class and use the codePointAt(int) method. It returns the ASCII value of character at the index specified.
There are other useful methods also in StringBuilder like codePointBefore(int) and appendCodePoint(int), which allow you to see the codepoint of the character before and append the character with the specified codepoint to the StringBuilder, respectively.
I assume here that the int value of each char should correspond to the Unicode code point of that character. If so, then the solution is trivial: you only need to type-cast between the char and int types. This is because in Java, a char is actually an Integral type just like an int. The char type can hold integer values that represent the code points of 16-bit Unicode characters ('\u0000' to '\uffff' or 0...65535).
The solution is to first, convert the String into a char[] using toCharArray. Then, simply cast each char into an int to get the Unicode code point value:
int capitalACodePoint = (int)'A';
Similarly, cast to char to get the value back:
char capitalA = (char) 65;
A runnable example:
String input = "hello";
List<Integer> codePoints = new ArrayList<>();
for (char c : input.toCharArray()) {
int codePoint = (int)c;
codePoints.add(codePoint);
System.out.println(String.format(
"char$ %d %s equals %d",
codePoints.size(), c, codePoint));
}
StringBuilder sb = new StringBuilder();
for (int codePoint : codePoints) {
sb.append((char) codePoint);
}
System.out.println(sb);
prints out
char$ 1 h equals 104
char$ 2 e equals 101
char$ 3 l equals 108
char$ 4 l equals 108
char$ 5 o equals 111
hello
This code also works with non-ASCII characters. Changing the input to
String input = "©†¿™";
prints out
char$ 1 © equals 169
char$ 2 † equals 8224
char$ 3 ¿ equals 191
char$ 4 ™ equals 8482
©†¿™
How to convert the Unicode of a number to the number itself in Java?
char c ='2';
int x =c;
// here x=unicode of 2, how can I put the 2 itself in x?
The most general solution is
int x = Character.digit(c, 10); // interpret c as a digit in base 10
The fastest solution, although it doesn't do anything to handle bad inputs, is
int x = c - '0'; // subtracts the Unicode representation of '0' from c
Use
int x = Character.getNumericValue(c);
or
int x = Integer.valueOf(String.valueOf(c));
Note that the second approach requires two conversions since Integer.valueOf can only handle other ints and Strings.
How can I convert couple of characters to int, to keep the question simple let's assume this :
char c1 = '1';
char c2 = '4';
char c3 = '5';
What would be the efficient way to get 145 type int.
int myInt = Integer.parseInt(""+c1+c2+c3);
""+c1 gives you a String containing the char c1, to which you append the characters c2 and c3. Then you use parseInt() to convert it to an integer.
A more straightforward (but less robust) method would be this:
int myInt = 100*(c1-'0') + 10*(c2-'0') + (c3-'0');
c1-'0' gives you the number represented by c1 as opposed to the character code. Then you simply shift things to the correct decimal places and add.
int myInt = (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0');
Here is a more general method to convert a char array to int:
int valueOf(char[] input){
int result = 0;
for(char c : input) {
result *= 10;
result += Character.digit(c, 10);
}
return result;
}
The most correct way to convert a single digit character to an int is Character.digit(char ch, int radix), which can handle values in bases besides 10.
Strings are ultimately backed by a char[], so you could do the following:
char c1 = '1';
char c2 = '4';
char c3 = '5';
int converted = Integer.parseInt(new String(new char[]{c1, c2, c3}));
There are probably several other perfectly good ways to do this.
char c = '0';
int i = 0;
System.out.println(c == i);
Why does this always returns false?
Although this question is very unclear, I am pretty sure the poster wants to know why this prints false:
char c = '0';
int i = 0;
System.out.println(c == i);
The answer is because every printable character is assigned a unique code number, and that's the value that a char has when treated as an int. The code number for the character 0 is decimal 48, and obviously 48 is not equal to 0.
Why aren't the character codes for the digits equal to the digits themselves? Mostly because the first few codes, especially 0, are too special to be used for such a mundane purpose.
The char c = '0' has the ascii code 48. This number is compared to s, not '0'. If you want to compare c with s you can either do:
if(c == s) // compare ascii code of c with s
This will be true if c = '0' and s = 48.
or
if(c == s + '0') // compare the digit represented by c
// with the digit represented by s
This will be true if c = '0' and s = 0.
The char and int value can not we directly compare we need to apply casting. So need to casting char to string and after string will pars into integer
char c='0';
int i=0;
Answer is like
String c = String.valueOf(c);
System.out.println(Integer.parseInt(c) == i)
It will return true;
Hope it will help you
Thanks
You're saying that s is an Integer and c (from what I see) is a Char.. so there you, that's the problem: Integer vs. Char comparation.