Java Integer to Hex intToHexStr(int src, int len, int code)

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

Description

int To Hex Str

License

Apache License

Declaration

public static String intToHexStr(int src, int len, int code) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {

    public static String intToHexStr(int src, int len, int code) {
        return longToHexStr(src, len, code);
    }//from   ww w .ja  v  a  2  s . c o m

    public static String longToHexStr(long src, int len, int code) {
        String HexStr = null;
        if (code == 0) {
            HexStr = asciiToHexStr(String.format("%d", src));
            int llen = len - HexStr.length();
            HexStr = fillString(HexStr, 0, llen, (byte) 30);
        } else if (code == 1) {
            byte[] tmp = new byte[16];
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < 16; i++) {
                tmp[i] = (byte) (src >> 4 * (16 - i - 1) & 0xf);
                sBuilder.append(String.format("%X", tmp[i]));
            }
            HexStr = sBuilder.toString();
            int llen = len - HexStr.length();
            HexStr = fillString(HexStr, 0, llen, (byte) 0);
        } else {
            throw new RuntimeException("code type is not support");
        }
        return HexStr.substring(0, len);
    }

    public static String asciiToHexStr(String src) {
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < src.length(); i++)
            sBuilder.append(String.format("%02X", Integer.valueOf(src.charAt(i))));
        return sBuilder.toString();
    }

    private static String fillString(String src, int direct, int len, byte fill) {
        if (len <= 0)
            return src;
        for (int i = 0; i < len; i += String.valueOf(fill).length()) {
            //left
            if (direct == 0) {
                src = String.valueOf(fill) + src;
            }
            //right
            else {
                src += String.valueOf(fill);
            }
        }
        return src;
    }
}

Related

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