Java Hex Calculate toHex(int n, int bytes)

Here you can find the source of toHex(int n, int bytes)

Description

Converts the given number into a hex string

License

Open Source License

Parameter

Parameter Description
n The number to convert
bytes The number of bytes to convert (1-4)

Return

The number represented in hex

Declaration

public static String toHex(int n, int bytes) 

Method Source Code

//package com.java2s;
//  in accordance with the terms of the license agreement accompanying it.

public class Main {
    private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**/*from   ww  w. ja va2 s .  c  o m*/
     * Converts the given number into a hex string
     * @param n The number to convert
     * @param bytes The number of bytes to convert (1-4)
     * @return The number represented in hex
     */
    public static String toHex(int n, int bytes) {
        // Sanity check the number of bytes
        if ((bytes < 1) || (bytes > 4)) {
            bytes = 4;
        }

        StringBuffer sb = new StringBuffer();

        for (int i = (bytes - 1); i >= 0; i--) {
            sb.append(hexDigit[(n >> ((i * 8) + 4)) & 0x0F]);
            sb.append(hexDigit[(n >> (i * 8)) & 0x0F]);
        }

        return sb.toString();
    }

    /**
     * Converts the given number into a hex string. The number
     * is assumed to be a 4-byte int
     * @param n The number to convert
     * @return The number represented in hex
     */
    public static String toHex(int n) {
        return toHex(n, 4);
    }
}

Related

  1. toHex(int i, String $default)
  2. toHex(int myByte)
  3. toHex(int n)
  4. toHex(int n)
  5. toHex(int n, Boolean bigEndian)
  6. toHex(int n, int s)
  7. toHex(int nibble)
  8. toHex(int num)
  9. toHex(int nybble)