LAST UPDATED: NOVEMBER 24, 2020
Java Long toHexString() Method
Java toHexString()
method is the part of the Long class of the java.lang
package. This method is used to return the hexadecimal equivalent of base 16 of the value passed as an unsigned long as a String. The unsigned long
value is the argument plus 2^64 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0
s.
Syntax:
public static String toHexString (long i)
Parameters:
The parameter passed is the long value of which the string representation of the equivalent hexadecimal of base 16 is to be returned.
Returns:
Returns the String representation of the parameter passed as equivalent base 16 hexadecimal value.
Example 1:
Here, a positive and a negative number is taken for a better understanding of the method.
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
}
}
Actual number is = 60
Hexadecimal equivalent is = 3c
Actual number is = -52
Hexadecimal equivalent is = ffffffffffffffcc
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.
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");
}
}
}
Enter the Number = 62
Actual Number is = 62
Hexadecimal representation is = 3e
********************************************
Enter the Number = -34
Actual Number is = -34
Hexadecimal representation is = ffffffffffffffde
*********************************************
Enter the Number = 0x477
Invalid Number
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.