RDPD
RDPD

Reputation: 565

ASCII value related query

I read that "When an integer is cast into a char, only its lower 16 bits of data are used; the other part is ignored". Based on this shouldn't i get the char value for '0041' as output.Instead i get 'A' as output ,which has an ASCII value of 65. Why does this happen??

  public class practice {
        public static void main(String[] args) {
           char ch = (char)0XAB0041;
           System.out.println(ch);
           char ch1= (char)65.25;
           System.out.println(ch1);
       }
 }

Will i get the same output if i myself consider only the lower 16 bits for casting.As below:

   char ch = (char)0041;
   System.out.println(ch);

Guys could anyone clear this problem that i am facing in comprehending the relation between unicode,ASCII and hexadecimal values... Thanks..

Upvotes: 2

Views: 452

Answers (3)

rahulserver
rahulserver

Reputation: 11205

0XAB0041 in decimal is:

11206721

in binary, it becomes:

101010110000000001000001

So taking last 16 bits, we have: 0000000001000001=65 in decimal If you see the ASCII table in this link, it is for 'A'

Hence, 0XAB0041 on casting to char, becomes 'A'

If you consider

   char ch = (char)0041;
   System.out.println(ch);

0041 is taken by java as octal literal with decimal value 4*8+1=33.So ASCII code for 33 decimal is !.

Hence the output will be:

!

Hence if you ask "Will i get the same output if i myself consider only the lower 16 bits for casting.", your answer is !(not) :)

Upvotes: 2

John3136
John3136

Reputation: 29266

0x0041 is decimal 65 which is ASCII 'A'.

65.25 would be truncated to 65, so it's still 'A'.

What were you expecting?

Upvotes: 4

bsd
bsd

Reputation: 2727

You are dealing with 0x41 which is 65(16 * 4 + 1) in decimal system. 'A' corresponds to ascii 0x41.

Upvotes: 2

Related Questions