Java Decimal to Hex decimalToHex(int n)

Here you can find the source of decimalToHex(int n)

Description

Returns the hexadecimal representation of the positive decimal number n.
A two digit representation is provided by this function always.

License

Open Source License

Parameter

Parameter Description
n a parameter

Declaration

private static String decimalToHex(int n) 

Method Source Code

//package com.java2s;
/*/*  w  w w . j a  va 2  s  .  c o  m*/
 *  Copyright (C) 2011 apurv
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Returns the hexadecimal representation of the positive decimal number n.<br>
     * A two digit representation is provided by this function always.
     * @param n
     * @return
     */
    private static String decimalToHex(int n) {
        assert (n >= 0);

        String invHexRepr = "";
        String hexRepr = "";
        String[] digits = { "0", "1", "2", "3", "4", "5", "6", "7", "8",
                "9", "A", "B", "C", "D", "E", "F" };
        while (n >= 16) {
            int remainder = n % 16;
            invHexRepr = invHexRepr + digits[remainder];
            n = n / 16;
        }
        invHexRepr = invHexRepr + digits[n];

        for (int i = invHexRepr.length() - 1; i >= 0; i--) {
            hexRepr = hexRepr + invHexRepr.substring(i, i + 1);
        }

        if (hexRepr.length() < 2) {
            hexRepr = "0" + hexRepr;
        }
        return hexRepr;
    }
}

Related

  1. dec2hex(int dec)
  2. decimal2hex(int d)
  3. decimalToHexa(final int d)