Java Integer to Hex intToHex(int val, char delim)

Here you can find the source of intToHex(int val, char delim)

Description

int To Hex

License

Open Source License

Declaration

public static String intToHex(int val, char delim) 

Method Source Code

//package com.java2s;
/**//from   w  w w.j  av  a 2  s. c o m
 * Copyright (c) 2014 xio4
 * Universal bot for lineage-like games (Archeage, Lineage2 etc)
 *
 * This file is part of Unibot.
 *
 * Unibot 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 {
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String intToHex(int val, char delim) {
        byte[] bytes = new byte[4];
        for (int i = 3; i >= 0; i -= 1) {
            bytes[3 - i] = (byte) ((val >>> (i * 8)) & 0xFF);
        }
        return bytesToHex(bytes, delim);
    }

    /**
     * Convert bytes to hex string
     * 
     * @param bytes
     * @return hex string
     */

    public static String bytesToHex(byte[] bytes, int size, char delim) {
        char[] hexChars;
        if (bytes == null)
            return "";
        if (delim == 0) {
            hexChars = new char[size * 2];
            for (int j = 0; j < size; j++) {
                int v = bytes[j] & 0xFF;
                hexChars[j * 2] = hexArray[v >>> 4];
                hexChars[j * 2 + 1] = hexArray[v & 0x0F];
            }
        } else {
            hexChars = new char[size * 3];
            for (int j = 0; j < size; j++) {
                int v = bytes[j] & 0xFF;
                hexChars[j * 3] = hexArray[v >>> 4];
                hexChars[j * 3 + 1] = hexArray[v & 0x0F];
                hexChars[j * 3 + 2] = delim;
            }
        }
        return new String(hexChars);
    }

    public static String bytesToHex(byte[] bytes, char delim) {
        return bytesToHex(bytes, bytes.length, delim);

    }
}

Related

  1. intToHex(int i)
  2. IntToHex(int i, int length)
  3. intToHex(int id)
  4. intToHex(int num)
  5. intToHex(int val)
  6. intToHex(int val, StringBuffer sb)
  7. intTohex2(int value)
  8. intToHex8(int value)
  9. intToHexBytes(int i)