![](/img/trans.png)
[英]Why the output getting differed in hexadecimal integer to character conversion?
[英]Converting a hexadecimal Integer into a character using explicit type conversion?
我編寫了以下代碼,但o / p不是預期的? 有人指導我嗎?
問題:編寫一個示例程序來聲明一個十六進制整數並使用顯式類型轉換將其轉換為一個字符?
class hexa
{
public static void main(String ar[])
{
int hex=0xA;
System.out.println(((char)hex));
}
}
請告訴我:為什么輸出有差異
/*code 1*/
int hex = (char)0xA;
System.out.println(hex);
/*code 2*/
int hex = 0xA;
System.out.println((char)hex);
int hex = 0xA;
System.out.println( (char)hex );
十六進制值0xA(或十進制10)是ASCII中的“\\ n”(新換行符)。
因此輸出。
編輯(感謝halex在評論中提供更正:
int hex = (char) 0xA;
System.out.println(hex); //here value of hex is '10', type of hex is 'int', the overloaded println(int x) is invoked.
int hex = 0xA;
System.out.println((char) hex); //this is equivalent to System.out.println( '\n' ); since the int is cast to a char, which produces '\n', the overloaded println(char x) is invoked.
我假設您要打印字母A
而不是print
使用printf
。
int hex=0xA;
System.out.printf("%X%n", hex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.