How to reconvert from int to AScII in java? [duplicate] - java

This question already has answers here:
Convert int to char in java
(18 answers)
Closed 1 year ago.
So what i understand is that if for example i have an int a = 49 and want to find out the ASCII equivalent to it, all i need to do is:
int a = 49;
System.out.println((char)a);
which has the Output: 1.
But how can i do this reversed? So lets say i have int a = 1 and i want the output to be 49?
I have already tried stuff like:
int a = 1;
System.out.println ((char)a);
But the output here is "." instead of 49.

This:
int a = 49;
System.out.println((char)a);
gives you the char whose internal value is 49, which is to say the unicode character '1'. There is no numerical conversion going on, it's just two ways to look at the same number.
In this:
int a = 1;
System.out.println((char)a);
you get the char whose internal value is 1, which is a unicode control character (ctrl/A, which probably won't be printed in any useful way). There is nothing there that can magically come up with the value 49.
If you had the character '1' then it's easy:
int a = '1';
System.out.println(a);
but this is practically the same as your first case; '1' and 49 are the same value.

Related

Converting a hexadecimal string to integer value without pre-made syntax

I'm taking a computer organization class in college. I was tasked with writing a java program that takes a user-inputted string, calls a function that converts said string into a hexadecimal integer, and then outputs the results.
The kicker is that I can't use any existing syntax to do this. for example, Integer.parseInt(__,16) or printf. It all neds to be hardcoded.
Now I'm not asking you to do my homework for me, just wanting to be put in the right direction.
So far, I've made this but can't seem to get the method created right:
import java.util.*;
public class Demo_Class
{
public static void main(String[] args)
{
Scanner AI = new Scanner(System.in);
String str;
System.out.println("Please input a hexadecimal number: ");
str = AI.nextLine();
converter(str);
}
public static int converter(String in)
{
String New = new String();
for(int i = 0; i<= in.length(); i++)
{
New += in.charAt(i);
System.out.println(New + 316);
}
return 0;
}
}
Consider this, lets says you have the hex value 1EC which in hex digits would be 1, E, C. In decimal they would be 1, 14, 12.
so set sum = 0.
sum = sum*16 + 1. sum is now 1
sum = sum*16 + 14 sum is now 30
sum = sum*16 + 12 sum is now 492
So 492 is the answer.
If you have a string of 1EC you need to convert to characters and then convert those characters to the decimal equivalent of hex values.
Try this on paper until you get the feel and then code it. You can check your results using the Integer method you mentioned.
#WJS gave a good hint, I'd just like to add that the charAt() returns the char, which is encoded in ASCII.
As you can see in the ASCII table, the characters A-F have decimal values from 65 to 70, while 0-9 go from 48 to 57 so you'll need to use them to convert the ASCII characters to their intended value.
To do so, you can either get the decimal value of a character by casting to short like short dec = (short)in.charAt(i);, or directly use the characters like char current = in.charAt(i) - 'A'.
With this in mind, all that's left is some calculation, I'll leave that as the homework. :)
Also:
you are looping one character more than needed, change the i <= in.length() to i < in.length(), since it's going from 0
I don't know what that 316 "magic number" is, if it does mean something, declare a variable with a meaningful name, like:
final int MEANINGFUL_NAME = 316;

Adding three different char in java as java variable and getting a number [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 4 years ago.
IntelliJ IDEA Capture
Why i am getting 152, I think it will give me an error.
Please explain it.
public class character {
public static void main(String[] args) {
char myCharValue1 = 'A';
char myCharValue2 = '2';
char myCharValue3 = '%';
System.out.println(myCharValue1 + myCharValue2 + myCharValue3);
}
}
That is because chars refer to a number, which in turn has an ASCII representation.
Looking at an ASCII table you can see that the chars A, 2 and % have following values respectivly: 65, 50 and 37.
Adding those numbers together, you'll end up with 152 which is what you got in your example.
To print out those chars you could use following:
System.out.printf("%s%s%s&n", myCharValue1 + myCharValue2 + myCharValue3);
Which will print A2% (and a newline)
The concatenation + is for String. What you're doing is adding the numeric values of your chars and printing them together.
If you start with "" and then use + as Patrick Parker shows in his comment, it will become concatenation instead of simple addition and you'll get the result you expect.

Java converting binary string to decimal [duplicate]

This question already has answers here:
How to convert binary string value to decimal
(15 answers)
Closed 5 years ago.
I tried to write a code that convert binary to decimal. But it gives me a huge result. Can you please tell me how to do it. I saw codes using remainder and give correct results but I really wonder what is the fault there in my code, thanks
double number = 0;
for (int i = 0; i < 16; i++) {
double temp = str.charAt(16-1 - i) * Math.pow(2, i);
number = number + temp;
}
Here is where your code went wrong:
str.charAt(16-1 - i) * Math.pow(2, i);
You just multiplied a char by a double. This will evaluate to the ASCII value of char times the double, not 0 or 1.
You need to convert this to an integer first:
Integer.parseInt(Character.toString(str.charAt(16-1 - i))) * Math.pow(2, i)
Or, you can just:
Integer.parseInt(binaryString, 2)
People here have already answered what went wrong. Doing Math.pow(2, i) on a character produced inconsistent result.
If you are going to convert binary value to an Integer this could help you.
Integer.parseInt(binaryString, 2)
Where the value 2 is the radix value.
Java documentation and similar SO Discussion on the same topic is available here.
When you use str.charAt(16-1-i), you get back a char, which represents a single letter. So you don't get the number 0 or 1, but the corresponding letters. As letters are represented as integers in Java, you don't get a type error. The number to represent a 0 letter is 48, for 1 it's 49. To convert your letter into the correct number, you have to write (str.charAt(16-1-i)-48) instead of str.charAt(16-1-i).

Java display length of int containing leading zeros

I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.
Here is what I tried:
//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;
This returns to length of 3
The other thing I tried was:
int number = 0123;
int length = String.valueOf(number).length();
This also returned a length of 3.
Are there any alternatives to how I can obtain this length?
Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to #DavidConrad and #DrewKennedy for the octal precision.
Instead declare it as a String if you want to keep the leading 0
String number = "0123";
int length = number.length();
And then when you need the number, simply do Integer.parseInt(number)
Why is the syntax of octal notation in java 0xx ?
Java syntax was designed to be close to that of C, see eg page 20 at
How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008
by James Gosling (20_Gosling_keynote.pdf):
In turn, this is the way how octal constants are defined in C language:
If an integer constant begins with 0x or 0X, it is hexadecimal. If it
begins with the digit 0, it is octal. Otherwise, it is assumed to be
decimal...
Note that this part is a C&P of #gnat answer on programmers.stackexchange.
https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java
Use a string instead:
String number = "0123";
int length = number.length(); // equals 4
This doesn't work with an int, as the internal representation of 0123 is identical to 123. The program doesn't remember how the value was written, only the actual value.
What you can do is declare a string:
String number = "0123";
int numberLengthWithLeadingZeroes = number.length(); // == 4
int numberValue = Integer.parseInt(number); // == 123
If you really want to include leading 0's you could always store it in an array of of characters
example:
char[] abc = String.valueOf(number).toCharArray();
Then obviously you can figure out the length of the array.
As several people have pointed out already though, integers don't have leading 0's.
String abc=String.format("%04d", yournumber);
for zero-padding with length=4.
Refer to this link .
http://download.oracle.com/javase/7/docs/api/java/util/Formatter.html
this might help u ..
Integers in Java don't have leading zeroes. If you assign the value 0123 to your int or Integer variable, it will be interpreted as an octal constant rather than a decimal one, which can lead to subtle bugs.
Instead, if you want to keep leading zeroes, use a String, e.g.
String number = "0123";
This way you can also measure the length:
String number = "0123";
System.out.println(number.length());

Get ASCII from char from string [duplicate]

This question already has answers here:
Get ASCII value at input word
(6 answers)
Closed 8 years ago.
I have a loop with i incrementing through a string, and I want to print that character, but its ASCII code.
myString = "90210";
for (int i = 0; i < myString.length(); i++) {
System.out.println(myString.charAt(i));
}
To output:
57
48
50
49
48
Obviously charAt() doesn't do this, but I need another method to append to it to get my desired result.
Just cast to an int so that you get the numerical value of the char, which consequently uses the overloaded println(int) method
System.out.println((int)myString.charAt(i));
System.out.println(myString.charAt(i) - '\0');
System.out.println(myString.charAt(i) - 0);

Categories