Java Integer to Hex intToHexStr(int i, int len)

Here you can find the source of intToHexStr(int i, int len)

Description

int To Hex Str

License

Open Source License

Parameter

Parameter Description
i a parameter
len a parameter

Declaration

public static String intToHexStr(int i, int len) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from ww  w  .  j a v  a2 s. c o m*/
     * 
     * @param i
     * @param len
     * @return
     */
    public static String intToHexStr(int i, int len) {
        String h = Integer.toHexString(i);
        boolean needFill = h.length() % 2 != 0;
        int l = needFill ? (h.length() / 2 + 1) : (h.length() / 2);
        if (needFill)
            h = "0" + h;

        StringBuffer buffer = new StringBuffer();
        for (int j = 0; j < (len - l); j++) {
            buffer.append("00");
            buffer.append(" ");
        }

        for (int j = 0; j < l; j++) {
            buffer.append(substr(h, j * 2, 2));
            buffer.append(" ");
        }
        if (buffer.charAt(buffer.length() - 1) == ' ')
            buffer.deleteCharAt(buffer.length() - 1);
        return buffer.toString();
    }

    /**
     * 
     * 
     * @param src
     * @param nStart
     * @param nLen
     * @return
     */
    public static String substr(String src, int nStart, int nLen) {
        if (src == null)
            return null;

        byte[] bySrc = src.getBytes();
        byte[] byRet = new byte[nLen];
        int i, j;
        for (i = nStart, j = 0; i < bySrc.length && j < nLen; i++, j++)
            byRet[j] = bySrc[i];

        return new String(byRet, 0, j);
    }

    /**
     * @param src
     * @param nStart
     * @return
     */
    public static String substr(String src, int nStart) {
        return substr(src, nStart, src.getBytes().length);
    }
}

Related

  1. intToHex8(int value)
  2. intToHexBytes(int i)
  3. intToHexChar(int i)
  4. intToHexChars(int n)
  5. intToHexLE(int val)
  6. intToHexStr(int src, int len, int code)
  7. IntToHexString(final int value)
  8. intToHexString(int _i)
  9. intToHexString(int i)