Java DoubleToRawLongBits Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to use the Double.doubleToRawLongBits() method in Java to get the long bit representation of a double value. This method is part of the java.lang.Double class and returns the bits of the argument as a long.

Import the necessary package

Import the java.lang.Double package in your Java code file using the following code:

import java.lang.Double;

Create a method for doubleToRawLongBits()

Create a method that will accept a double value and return the equivalent long value in bits using the doubleToRawLongBits() method. Add the following code to your Java file:

public long getLongBits(double value) {
    return Double.doubleToRawLongBits(value);
}

Use the method

Now, create some double numbers and use the getLongBits() method to get their respective bit representations as long values. Use the following code to create and print some double numbers and their respective long bit representations:

public static void main(String[] args) {
    DoubleToRawLongBitsDemo demo = new DoubleToRawLongBitsDemo();
    double a = 10.002;
    double b = -60.123456789;
    double c = 0.12345;
    System.out.println("Double a = " + a);
    System.out.println("Double a in binary = " + Long.toBinaryString(demo.getLongBits(a)));
    System.out.println("\nDouble b = " + b);
    System.out.println("Double b in binary = " + Long.toBinaryString(demo.getLongBits(b)));
    System.out.println("\nDouble c = " + c);
    System.out.println("Double c in binary = " + Long.toBinaryString(demo.getLongBits(c)));
}

Compile and run the program

Save the Java file and compile it using the following command in your terminal:

javac DoubleToRawLongBitsDemo.java

Now, run the bytecode file using the following command:

java DoubleToRawLongBitsDemo

Understand the output

The output of the program should be something like this:

Double a = 10.002
Double a in binary = 0100000000010010001100110011001100110011001100110011001100110011

Double b = -60.123456789
Double b in binary = 1100000001011111010110011011010100001110010100010100001111000110

Double c = 0.12345
Double c in binary = 0011111110110001010010100011110101110000111101011100001010100000

Here, we can see that the getLongBits() method returns the long bit representation of a given double input. We have used the Long.toBinaryString() method to convert the long value to its binary representation.

Summary

In this lab, we learned how to use the Double.doubleToRawLongBits() method in Java to return the long bit representation of a double value. We have created a Java program that accepts a double value and returns its respective long bit representation. We have also used the Long.toBinaryString() method to convert the long value to its binary representation.

Other Java Tutorials you may like