I found an exercise to convert from hex to decimal using casting, but I did not understand how that decimal + 'A' - 10 worked. Can anybody explain me?
code is here:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a decimal value (0-15):");
int decimal = input.nextInt();
if (decimal <= 9 && decimal >= 0) {
System.out.println("The hex value is: " + decimal);
}
else if (decimal >= 10 && decimal <= 15) {
System.out.println("The hex value is " + (char)(decimal + 'A' - 10));
}
else {
System.out.println("It's an invalid input.");
}
}
}
Thanks.
The alphabetical characters in Unicode have sequential codes:
A = 65
B = 66
C = 67
D = 68
...
So, the value of (char)('A'+1) is the same as 'B', as the char value 'A' is interpreted as 65 when used in an arithmetic expression, and then the +1 makes it 66, and then you cast it as char again, it's 'B'.
So what you have there is the value of 'A' plus the difference between the decimal and 10 (which is 0 through 5). This will give you the values 'A' + 0, 'A' + 1, 'A' + 2 etc, which means 'A', 'B', 'C' respectively when you calculate it.
Each char has integer value associated with it. Hence casting int to (char) will yield to char value.
Related
I am new to Java Programming and I stumbled upon below copy pasted code ( which I found from: How to sum digits of an integer in java?)
I am struggling to understand this code and basically would like an explanation on the following line:
sum += c -'0';
What does this line evaluate to? and what is the purpose of -'0' ?
thanks all in advance.
import java.util.Scanner;
public class RandomPractice1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter some digits: ");
String digits = input.nextLine(); //try digits 55
int sum = 0;
for (char c : digits.toCharArray()) {
sum += c -'0';
}
System.out.printf("sum of numbers %s is %d\n", digits, sum); //the answer is 10
} }
char values in Java have an integer representation, but it doesn't correspond to their integer value. '0' is 48, '1' is 49, and so on.
Assuming you only enter decimal digits, then subtracting '0' from each char is one way to get their apparent integer values, so that when you sum them you get the expected total.
import java.util.*;
public class Dec2Hex {
public static void main (String[] args){
Scanner input new Scanner (System.in);
System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
char hexDigit = (0 <= hexValue && hexValue <= 9)?
(char)(hexValue + '0'): (char)(hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal/16;
}
System.out.println("The hex number is " + hex);
}
}
This is an example in my book. I understand most of it but can't quite grasp a few parts. The example uses 1234 as the decimal entered.
The remainder of 1234/16 is 2 so hexValue is 2. Therefore hexDigit is 2 + '0'. But hexDigit is a character so what is the meaning of combining or adding 2 and '0'?
The final answer is 4D2. Where in the code did we ever provide instruction for any letter other than 'A'? How did it come up with a 'D'?
Thank you!
I understand now that the second part of the condition is takin a number like "13", subtracting 10 and adding that to 'A'. 3 + 'A' is 'D' in unicode.
I still do not understand adding the '0' to the first part of the condition. Couldn't we just say (char)(hexValue)? Why add '0'?
Thanks!
The remainder of 1234/16 is 2 so hexValue is 2. Therefore hexDigit is 2 + '0'. But hexDigit is a character so what is the meaning of combining or adding 2 and '0'?
The value 2 is an integer value, however the variable type is char. No problem in assigning such a value to a char variable, however this would result in the 0x02 character/byte, which is a control character, not a visible character to display. The digits in the ASCII table to display begins at 0x30 (which is the digit '0'). To get the character value to save in the char variable you add your calculated value 2 with the offset 0x30. To make this calculation easier you use the expression '0'. This is the exact value of 0x30 (or 48 in decimal).
The final answer is 4D2. Where in the code did we ever provide instruction for any letter other than 'A'? How did it come up with a 'D'?
The calculation is as follow:
1234 divided by 16 is 77 with a remainder of 2.
77 divided by 16 is 4 with a remainder of 13 (which is D).
4 divided by 16 is 0 with a remainder of 4.
This results in 4D2. To verify:
4*16*16 + 13*16 + 2 = 1234
Every char has a value number between 0 to 256, each of these numbers encode a printable sign.
For example the value of '0' is 48, and the value of 'A' is 65.
So when adding a constant offset to a character it's like going to that offset in that encoding.
For example '0' + 5 is '5', or 'A' + 3 is 'D'.
So as for your questions:
'0' + 2 is '2', i.e. the printable character of 2.
In the code hexValue had the value of 13, so hexDigit got the value (hexValue - 10 + 'A'), which is (hexValue - 10 + 'A') = 13 - 10 + 'A' = 'A' + 3 = 'D'.
2 + '0' = 2 + 48 = 50
(char)50 = '2'
Note that
'0' = 48
'1' = 49
'2' = 50
...
'9' = 57
Check ASCII Table to learn more about ASCII values.
Demo:
public class Main {
public static void main(String[] args) {
System.out.println((char) 50);
}
}
Output:
2
Ascii table is used for char type, so characters can be represented by decimal values. For example:
'0' in decimal 48
'1' in decimal 49
'2' in decimal 50
...
'9' in decimal 57
'A' in decimal 65
'B' in decimal 66
'C' in decimal 67
'D' in decimal 68
...
'Z' in decimal 90
'a' in decimal 97
'b' in decimal 98
...
'z' in decimal 122
Having that in mind your here are the answers to your questions:
We focus on the line
char hexDigit = (0 <= hexValue && hexValue <= 9)?
(char)(hexValue + '0'): (char)(hexValue - 10 + 'A');
The remainder of 1234/16 is 2 so hexValue is 2. Therefore hexDigit is
2 + '0'. But hexDigit is a character so what is the meaning of
combining or adding 2 and '0'?
For this question the part of interest is
(char)(hexValue + '0')
The value hexValue is 2, so hexValue + '0' is 50, because in ascii table '0' has decimal value 48. Than value of 50 is casted to char, which by ascii table is '2'.
The final answer is 4D2. Where in the code did we ever provide
instruction for any letter other than 'A'? How did it come up with a
'D'?
For this question the part of interest is
(char)(hexValue - 10 + 'A')
The value hexValue is 13. By asci table 'A' has value of 65 and 'D' has value of 68. So hexValue - 10 is 3 and when we sum 3 and 'A' we get 68. Finally we do cast to char and get 'D'.
You can easyly test the answers by executing this piece of code:
public class Main {
public static void main(String[] args) {
System.out.println("Decimal value: "+(2+'0')+" Char value:" +(char)(2+'0'));
System.out.println("Decimal value: "+(3 + 'A')+" Char value: "+ (char)(3+'A'));
}
}
Regards
I've been searching for a solution to my problem for days but can't get a spot-on answer when looking at previously answered questions/ blogs / tutorials etc. all over the internet.
My aim is to write a program which takes a decimal number as an input and then calculates the hexadecimal number and also prints the unicode-symbol of said hexadecimal number (\uXXXX).
My problem is I can't "convert" the hexadecimal number to unicode. (It has to be written in this format: \uXXXX)
Example:
Input:
122 (= Decimal)
Output:
Hexadecimal: 7A
Unicode: \u007A | Unicode Symbol: Latin small letter "z"
The only thing I've managed to do is print the unicode (\u007A), but I want the symbol ("z").
I thought if the unicode only has 4 numbers/letters, I would just need to "copy" the hexadecimal into the code and fill up the remaining places with 0's and it kinda worked, but as I said I need the symbol not the code. So I tried and tried, but I just couldn't get the symbol.
By my understanding, if you want the symbol you need to print it as a string.
But when trying it with a string I get the error "illegal unicode escape".
It's like you only can print pre-determined unicodes and not "random" ones generated on the spot in relation of your input.
I'm only a couple days into Java, so apologies if I have missed anything.
Thank you for reading.
My code:
int dec;
int quotient;
int rest;
int[]hex = new int[10];
char[]chars = new char[]{
'F',
'E',
'D',
'C',
'B',
'A'
};
String unicode;
// Input Number
System.out.println("Input decimal number:");
Scanner input = new Scanner(System.in);
dec = input.nextInt();
//
// "Converting to hexadecimal
quotient = dec / 16;
rest = dec % 16;
hex[0] = rest;
int j = 1;
while (quotient != 0) {
rest = quotient % 16;
quotient = quotient / 16;
hex[j] = rest;
j++;
}
//
/*if (j == 1) {
unicode = '\u000';
}
if (j == 2) {
unicode = '\u00';
}
if (j == 3) {
unicode = '\u0';
}*/
System.out.println("Your number: " + dec);
System.out.print("The corresponding Hexadecimal number: ");
for (int i = j - 1; i >= 0; i--) {
if (hex[i] > 9) {
if (j == 1) {
unicode = "\u000" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 2) {
unicode = "\u00" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 3) {
unicode = "\u0" + String.valueOf(chars[16 - hex[i] - 1]);
}
System.out.print(chars[16 - hex[i] - 1]);
} else {
if (j == 1) {
unicode = "\u000" + Character.valueOf[hex[i]);
}
if (j == 2) {
unicode = "\u00" + Character.valueOf(hex[i]);
}
if (j == 3) {
unicode = "\u0" + Character.valueOf(hex[i]);
}
System.out.print(hex[i]);
}
}
System.out.println();
System.out.print("Unicode: " + (unicode));
}
It's not an advanced code whatsoever, I wrote it exactly how I would calculate it on paper.
Dividing the number through 16 until I get a 0 and what remains while doing so is the hexadecimal equivalent.
So I put it in a while loop, since I would divide the number n-times until I got 0, the condition would be to repeat the division until the quotient equals zero.
While doing so the remains of each division would be the numbers/letters of my hexadecimal number, so I need them to be saved. I choose an integer array to do so. Rest (remains) = hex[j].
I also threw a variable in the called "j", so I would now how many times the division was repeated. So I could determine how long the hexadecimal is.
In the example it would 2 letters/numbers long (7A), so j = 2.
The variable would then be used to determine how many 0's I would need to fill up the unicode with.
If I have only 2 letters/numbers, it means there are 2 empty spots after \u, so we add two zeros, to get \u007A instead of \u7A.
Also the next if-command replaces any numbers higher than 9 with a character from the char array above. Basically just like you would do on paper.
I'm very sorry for this insanely long question.
U+007A is the 3 bytes int code pointer.
\u007A is the UTF-16 char.
A Unicode code pointer, symbol, sometimes is converted to two chars and then the hexadecimal numbers do not agree. Using code pointers hence is best. As UTF-16 is just an encoding scheme for two-bytes representation, where the surrogate pairs for 3 byte Unicode numbers do not contain / or such (high bit always 1).
int hex = 0x7A;
hex = Integer.parseUnsignedInt("007A", 16);
char ch = (char) hex;
String stringWith1CodePoint = new String(new int[] { hex }, 0, 1);
int[] codePoints = stringWith1CodePoint.codePoints().toArray();
String s = "𝄞"; // U+1D11E = "\uD834\uDD1E"
You can simply use System.out.printf or String.format to do what you want.
Example:
int decimal = 122;
System.out.printf("Hexadecimal: %X\n", decimal);
System.out.printf("Unicode: u%04X\n", decimal);
System.out.printf("Latin small letter: %c\n", (char)decimal);
Output:
Hexadecimal: 7A
Unicode: u007A
Latin small letter: z
Background:
I am making a simple base converter for a class assignment. I am fairly close to completion but need to tidy up the conversion algorithm to convert the user inputted value (in a given base) to a base 10 value.
Attempt:
import java.util.Scanner;
public class BaseConverter {
public static void main(String[] args) {
String numIn, intro1, prompt1, prompt2, output1;
int baseIn;
double numOut;
boolean flag = true;
Scanner kb = new Scanner(System.in);
intro1 = "This program converts values in different number bases to a decimal value.";
prompt1 = "Type in a number base (2 - 9): ";
while (flag == true){
System.out.println(intro1);
System.out.println(prompt1);
baseIn = kb.nextInt();
//Checking base value for outliers outside given range
if (baseIn < 2 || baseIn > 9) {
System.out.println("Base must be between 2 and 9");
System.exit(1);
}
prompt2 = "Type in a base "+baseIn+" number: ";
System.out.println(prompt2);
numIn = kb.next();
// System.out.println(numStore);
int counter = 0;
// Let's pretend baseIn is 3 and i starts at 3
for (int i = numIn.length(); i >= 1; i--){
numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));
System.out.println(numOut);
}
}//while
}// method
}//class
The problem:
This line does not return the expected value
numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));
For example, in string "10", numOut should be (0*(2*0)) or zero on the first iteration of the for loop. Instead, it returns 48.0.
My Thoughts:
I have a sneaking suspicion it has to do with the charAt() method as debugging the Math.pow() method showed it returning expected values. Suppose it's something to do with all the different variable types? I'm unsure.
Yes you're right charAt is the problem.
When you type let's say "10", the integer value of the character '0' is 48 and for '1' it's 49 according to the encoding table Java uses to encode characters.
If you take a look at it, you see that 0 is encoded as 0x0030 = 3*16^1 = 48, 1 as 0x0031 = 3*16^1 + 1*16^0 = 49 and so on.
If you want to get the numeric value of the character itself you can use
numOut = Character.getNumericValue(numIn.charAt(i-1)) * Math.pow(baseIn, counter++);
The charAt method returns the char of your input, in this case '0', not 0. The Unicode value for the char '0' is not 0, it's 48.
Fortunately, the values '0' through '9' are consecutive Unicode values, 48 through 57 respectively, so you can "subtract" out the 48 by subtracting '0' before multiplying.
numOut = ( (numIn.charAt(i-1) - '0') * Math.pow(baseIn, counter++));
You'll still need to validate that what the user typed is in fact a valid "digit" in the chosen base.
You'll also want to add the values of numOut together to get the decimal result at the end.
I am trying to come up with a function that accepts a character and a number. The number is the number of times the character should be "rotated". The accepted ASCII codes are 32 to 126.
Example of rotate = If a character "A" was rotated twice, it would end up as the character "C". If "A" was rotated three times, it would end up as the letter "D". If you look at the ASCII table:
http://www.jimprice.com/ascii-0-127.gif
Given my limit of the ASCII value being 32 to 126... ascii value 065 rotated would be ascii value 067. ascii value 124 rotated 5 times would be ascii value 34.
For example:
if I passed the function "!" (ASCII code 33) and the number 2, the
output character should be "#" (ASCII code 35).
if I passed "}"
(ASCII code 125) and the number 3, I should get the output character
"!" (ASCII code 33).
What is the best way to accomplish this in java (can it support negative numbers for the distance to rotate instead of just positive if you want to rotate the other way around)?
Try something like:
static char rotate(char c, int distance) {
assert 32 <= c && c < 127;
if (distance < 0) distance = distance % (127 - 32) + 127 - 32;
return (char) ((c + distance - 32) % (127 - 32) + 32);
}
Edit: Added the if (distance... line to support negative distances.
Do like this
public static char numToChar(int num,int rotate){
int result = num+rotate;
if(result>126){
result =31+(result-126);
}
return (char)result;
}
System.out.println(numToChar(33,2));
System.out.println(numToChar(125,3));
Output
#
!
You could use this approach
public static char rotateChar(char in, int shift) {
/* cast char to int */
int v = (int) in;
/* to cover wrap-around */
v += (shift % 95);
/* 32 - 126 = -95 */
return (char) ((v > 126) ? v - 95 : v);
}
public static void main(String[] args) {
System.out.printf("! + 2 = %s\n",
String.valueOf(rotateChar('!', 2)));
System.out.printf("} + 3 = %s\n",
String.valueOf(rotateChar('}', 3)));
System.out.printf("b - 1 = %s\n",
String.valueOf(rotateChar('b', -1)));
}
! + 2 = #
} + 3 = !
b - 1 = a
Try This.
public static void main(String[] args) {
String ascii;
String rotate;
Scanner in = new Scanner(System.in);
System.out.println("Enter ASCII Character");
ascii = in.nextLine();
System.out.println("Enter Rotate value");
rotate = in.nextLine();
int output=(Integer.parseInt(ascii)+Integer.parseInt(rotate))% 126;
if(output<32) output=output+32;
System.out.println("output="+output);
System.out.println(Character.toString ((char) output));
}