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
Related
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.
I have a biginteger
BigInteger b = new BigInteger("2389623956378561348065123807561278905618906");
And I need to print all its digits (2, 3, 8, and so on...). How can I do it?
Convert to char array, then decrease from each char the ASCII code of '0' char, to get digits between 0 and 9
char[] digits = b.toString().toCharArray();
for (char digit : digits) {
digit -= '0';
System.out.println((int)digit);
}
Note that if you just want to print, don't reduce the '0' ASCII value, and don't cast to int when printing
Already answered by Evan Knowles and user3322273, but here is another implementation:
byte[] digits = b.getBytes();
for (byte digit : digits) {
System.out.println (digit & 0xf);
}
What it does is that it masks the (ASCII) value of the digit. For example:
'0' = 48 | In ASCII and Unicode - Decimal
= 110000 | In binary
Hence, if we obtain the last four bits, then we can get the number. So
48 & 0xf (i.e. 15)
= 11 0000
& 00 1111
= 0000
= 0 | Ultimately in decimal.
There is something that doesn't quite make sense to me. Why does this:
public static int[] countNumbers(String n){
int[] counts = new int[10];
for (int i = 0; i < n.length(); i++){
if (Character.isDigit(n.charAt(i)))
counts[n.charAt(i)]++;
}
return counts;
}
bring up an ArrayOutOfBounds error while this:
public static int[] countNumbers(String n){
int[] counts = new int[10];
for (int i = 0; i < n.length(); i++){
if (Character.isDigit(n.charAt(i)))
counts[n.charAt(i) - '0']++;
}
return counts;
}
does not? The only difference between the two examples is that the index for counts is being subtracted by zero in the second example. If I'm not mistake, shouldn't the first example display correctly since the same value is being checked?
Here are the value being passed for the two methods:
System.out.print("Enter a string: ");
String phone = input.nextLine();
//Array that invokes the count letter method
int[] letters = countLetters(phone.toLowerCase());
//Array that invokes the count number method
int[] numbers = countNumbers(phone);
This is the problem:
counts[n.charAt(i)]++;
n.charAt(i) is a character, which will be converted to an integer. So '0' is actually 48, for example... but your array only has 10 elements.
Note that the working version isn't subtracting 0 - it's subtracting '0', or 48 when converted to an int.
So basically:
Character UTF-16 code unit UTF-16 code unit - '0'
'0' 48 0
'1' 49 1
'2' 50 2
'3' 51 3
'4' 52 4
'5' 53 5
'6' 54 6
'7' 55 7
'8' 56 8
'9' 67 9
The code is still broken for non-ASCII digits though. As it can only handle ASCII digits, it would be better to make that explicit:
for (int i = 0; i < n.length(); i++){
char c = n.charAt(i);
if (c >= '0' && c <= '9') {
counts[c - '0']++;
}
}
'0' is quite different from 0. '0' is the code of the "zero" character.
problem is in the line counts[n.charAt(i)]. here n.charat(i) may return values larger than 9;
The confusion here is that you're thinking '0' == 0. This is not true. When treated as a number, '0' has the ASCII value for the character 0, which is 48.
Because n.charAt(i) returns a character which is then boxed to a number. In this case the character 0 is actually ASCII value 48.
By subtracting character '0', you are subtracting the value 48 and taking the index into a range that is 0-9 because you've checked the character is a valid digit.
I'm trying to make a UUencode algorithm and part of my code contains this:
for(int x = 0; x < my_chars.length; x++)
{
if((x+1) % 3 == 0)
{
char first = my_chars[x-2];
char second = my_chars[x-1];
char third = my_chars[x];
int first_binary = Integer.parseInt(Integer.toBinaryString(first));
int second_binary = Integer.parseInt(Integer.toBinaryString(second));
int third_binary = Integer.parseInt(Integer.toBinaryString(third));
int n = (((first << 8) | second) << 8) | third;
System.out.print(my_chars[x-2] + "" + my_chars[x-1] + my_chars[x] + Integer.toBinaryString(n));
}
}
System.out.println();
System.out.println(Integer.toBinaryString('s'));
What I'm trying to achieve is to combine those 8 bits from the chars that I get into a big 24 bits int. The problem I'm facing is that the result is a 23 bit int. Say my first 3 chars were:
'T' with a binary representation of 01010100
'u' with a binary representation of 01110101
'r' with a binary representation of 01110010
The result that I get from my program is a int formed from these bits:
10101000111010101110010
Which is missing the 0 at the beginning from the representation of 'T'.
Also I have included the last 2 lines of code because the binary string that I get from 's' is: 1110011 which is missing the 0 at the beginning.
I have checked if I scrolled by mistake to the right but it does not seem that I have done so.
The method Integer.toBinaryString() does not zero-pad the results on the left; you'll have to zero-pad it yourself.
This value is converted to a string of ASCII digits in binary (base 2)
with no extra leading 0s.
Here is the code snippet i am trying to figure out whats happening
String line = "Hello";
for (int i = 0; i < line.length(); i++) {
char character = line.charAt(i);
int srcX = 0;
if (character == '.') {
}else{
srcX = (character - '0') * 20;
System.out.println("Character is " + (character - '0') +" " + srcX);
}
}
and executing that code will result to this
Character is 24 480
Character is 53 1060
Character is 60 1200
Character is 60 1200
Character is 63 1260
How a character minus the string which is "0" result in integer?? and where does the system base its answer to have 24,53,60,60,63?
You are allowed to subtract characters because char is an integer type.
The value of a character is the value of its codepoint (more or less, the details are tricky due to Unicode and UTF-16 and all that).
When you subtract the character '0' from another character, you are essentially subtracting 48, the code point of the character DIGIT ZERO.
So, for example, something like '5' - '0' would evaluate to 53 - 48 = 5. You commonly see this pattern when "converting" strings containing digits to numeric values. It is not common to subtract '0' from a character like 'H' (whose codepoint is 72), but it is possible and Java does not care. It simply treats characters like integers.
http://www.ascii.cl/
'0' is 48 in ascii
'H' is 72.
Therefore 72-48 gives you 24