Java Integer to intToLengthHexByte(int args, int hexLength)

Here you can find the source of intToLengthHexByte(int args, int hexLength)

Description

int To Length Hex Byte

License

Apache License

Declaration

public static byte[] intToLengthHexByte(int args, int hexLength) 

Method Source Code

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

public class Main {

    public static byte[] intToLengthHexByte(int args, int hexLength) {
        String s = Integer.toHexString(args);
        //      if (s.length() % 2 != 0) {
        //         s = "0" + s;
        //      }
        byte[] re = hexToLengthHexByte(s);
        if (s.length() >= hexLength * 2) {
            return re;
        } else {/* www .j  av  a2 s.  com*/
            byte[] newb = new byte[hexLength];
            System.arraycopy(re, 0, newb, hexLength - re.length, re.length);
            return newb;
        }
    }

    public static byte[] intToLengthHexByte(Long args, int hexLength) {
        String s = Long.toHexString(args);
        //      if (s.length() % 2 != 0) {
        //         s = "0" + s;
        //      }
        byte[] re = hexToLengthHexByte(s);
        if (s.length() >= hexLength * 2) {
            return re;
        } else {
            byte[] newb = new byte[hexLength];
            System.arraycopy(re, 0, newb, hexLength - re.length, re.length);
            return newb;
        }
    }

    public static byte[] hexToLengthHexByte(String hexString) {
        if (hexString == null || "".equalsIgnoreCase(hexString)) {
            return null;
        }
        StringBuffer str = new StringBuffer();
        if (hexString.length() % 2 != 0) {
            str.append("0");
        }
        str.append(hexString);
        hexString = str.toString().toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}

Related

  1. intToFourChars(int value)
  2. intToGoodBadSimple(int i)
  3. intToID(int ID)
  4. intToInteger(int[] array)
  5. intToIntegerArray(int[] array)
  6. intToLetter(int index)
  7. intToLex(int v)
  8. intToLittleEndian(int val)
  9. intToLittleEndian(int value)