Converts a long to a string representing this value in hexadecimal format. - Java java.lang

Java examples for java.lang:int Format

Description

Converts a long to a string representing this value in hexadecimal format.

Demo Code


//package com.java2s;

public class Main {
    /**//ww w  . j  a  v a 2 s . c o m
     * Various powers with 16 as base and the index as power.
     * I absolutly don't take any warranty that everything is correct and I don't
     * worry about this since longToHexString() is not used (I found out too late that
     * the Java-libs already contain such a function).
     */
    static long[] pow16 = { 1l, 16l, 256l, 4096l, 65536l, 1048576l,
            16777216l, 268435456l, 4294967296l, 68719476736l,
            1099511627776l, 17592186044416l, 281474976710656l,
            4503599627370496l, 72057594037927936l, 1152921504606846976l };

    /**
     * Converts a long to a string representing this value in hexadecimal format.
     * @param value the number as long-value
     * @return the number as hexadecimal string
     */
    static String longToHexString(long value) {

        String result = "";
        long rest = value;

        while (rest > 0) {
            byte power = 1;
            // find the highest power of 16 which is smaller than rest
            while (pow16[power] < rest) {
                power++;
            }
            power--;
            int multiply = (int) (rest / pow16[power]);
            rest = rest - (multiply * pow16[power]);
            String digit = "";
            if (multiply < 10) {
                digit = String.valueOf(multiply);
            } else if (multiply == 10) {
                digit = "A";
            } else if (multiply == 11) {
                digit = "B";
            } else if (multiply == 12) {
                digit = "C";
            } else if (multiply == 13) {
                digit = "D";
            } else if (multiply == 14) {
                digit = "E";
            } else if (multiply == 15) {
                digit = "F";
            }

            result = result + digit;
        }
        return result;
    }
}

Related Tutorials