How do I display file contents in hexadecimal?

In this program we read the file contents byte by byte and then print the value in hexadecimal format. As an alternative to read a single byte we can read the file contents into array of bytes at once to process the file faster.

package org.kodejava.io;

import java.io.FileInputStream;

public class HexDumpDemo {
    public static void main(String[] args) throws Exception {
        // Open the file using FileInputStream
        String fileName = "F:/Wayan/Kodejava/kodejava-example/data.txt";
        try (FileInputStream fis = new FileInputStream(fileName)) {
            // A variable to hold a single byte of the file data
            int i = 0;

            // A counter to print a new line every 16 bytes read.
            int count = 0;

            // Read till the end of the file and print the byte in hexadecimal
            // valueS.
            while ((i = fis.read()) != -1) {
                System.out.printf("%02X ", i);
                count++;

                if (count == 16) {
                    System.out.println();
                    count = 0;
                }
            }
        }
    }
}

And here are some result from the file read by the above program.

31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 
37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 
33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 
39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 
35 36 37 38 39 30 0A 

How do I convert decimal to hexadecimal?

To convert decimal number (base 10) to hexadecimal number (base 16) we can use the Integer.toHexString() method. This method takes an integer as parameter and return a string that represent the number in hexadecimal.

To convert back the number from hexadecimal to decimal number we can use the Integer.parseInt() method. This method takes two argument, the number to be converted, which is the string that represent a hexadecimal number. The second argument is the radix, we pass 16 which tell the method if the string is a hexadecimal number.

package org.kodejava.lang;

public class ToHexadecimalExample {
    public static void main(String[] args) {
        // Converting a decimal value to its hexadecimal representation 
        // can be done using Integer.toHexString() method.
        System.out.println(Integer.toHexString(1976));

        // On the other hand to convert hexadecimal string to decimal
        // we can use Integer.parseInt(string, radix) method, 
        // where radix for hexadecimal is 16.
        System.out.println(Integer.parseInt("7b8", 16));
    }
}