Java Integer.toHexString()方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-tohexstring-method

Java toHexString()方法是java.lang包的Integer类的一部分。此方法用于将作为无符号整数传递的值的 16 进制等效值作为字符串返回。

例如:对于值 60,返回的等效十六进制字符串将是 CF。

语法:

public static String toHexString (int i)

参数:

传递的参数是一个整数值,它的字符串表示形式是以 16 为基数的等效十六进制数。

返回:

返回作为等效的 16 进制基值传递的参数的字符串表示形式。

例 1:

这里,为了更好地理解该方法,取一个正数和一个负数。

import java.lang.Integer;

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        int i = 132; 
        int j = -52;
        System.out.println("Actual number is = " + i);  
        System.out.println("Hexadecimal equivalent is = " + Integer.toHexString(i)); //returns the integer value in hexadecimal base 16 as a string

        System.out.println("Actual number is = " + j);  
        System.out.println("Hexadecimal equivalent is = " + Integer.toHexString(j)); //returns the integer value in hexadecimal base 16 as a string        
    }  
}

实际数为= 132 十六进制等值为= 84 实际数为= -52 十六进制等值为= ffffffcc

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.util.Scanner;  

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        try
        {
            System.out.print("Enter the Number = ");  
            Scanner sc = new Scanner(System.in);  
            int i = sc.nextInt();  
            System.out.println("Actual Number is  = " + i);  
            System.out.println("Hexadecimal representation is = " + Integer.toHexString(i)); //returns the integer value in hexadecimal base 16 as a string 
        }  
        catch(Exception e)
        {
            System.out.println("Invalid Number");
        }
    }
}

输入数字= 674 实际数字为= 674 十六进制表示为= 2 a2

                                                                  • T4】输入数字= -85 实际数字为= -85 十六进制表示为= ffffffab
                                                                                                                • *输入数字= 0x55 无效数字

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。