Java Long.toHexString()方法

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

Java toHexString()方法是java.lang包的 Long 类的一部分。此方法用于返回作为无符号长字符串传递的值的 16 进制等效值。无符号的long值是参数加上 2^64,如果参数是负的;否则,它等于参数。该值被转换为十六进制的 ASCII 数字串(基数 16),没有额外的前导0 s。

语法:

public static String toHexString (long i)

参数:

传递的参数是长值,其字符串表示形式为 16 进制。

返回:

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

例 1:

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

import java.lang.Long;

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

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

实际数为= 60 十六进制等值为= 3c 实际数为= -52 十六进制等值为= ffffffffffffcc

例 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);  
          long i = sc.nextLong();  
          System.out.println("Actual Number is  = " + i);  
          System.out.println("Hexadecimal representation is = " + Long.toHexString(i)); //returns the long value in hexadecimal base 16 as a string 
        }  
        catch(Exception e)
        {
          System.out.println("Invalid Number");
        }
    }
}

输入数字= 62 实际数字为= 62 十六进制表示为= 3e

                                                                          • T4】输入数字= -34 实际数字为= -34 十六进制表示为= ffffffffffffffde
                                                                                                                • *输入数字= 0x477 无效数字

实时示例:

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