Java Long to Hex longToHexStr(long src, int len, int code)

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

Description

long To Hex Str

License

Apache License

Declaration

public static String longToHexStr(long src, int len, int code) 

Method Source Code

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

public class Main {

    public static String longToHexStr(long src, int len, int code) {
        String HexStr = null;/* w ww  .j a v a  2  s.  c om*/
        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. longToHex(long num)
  2. longToHex(long val, char delim)
  3. longToHexBytes(final long v)
  4. longToHexBytes(long i)
  5. longToHexChars(long value, int length)
  6. LongToHexString(final long value)
  7. longToHexString(long n, int digits)
  8. longToHexString(long num)
  9. longToHexString(long number)