Java Integer to Hex intToHexBytes(int i)

Here you can find the source of intToHexBytes(int i)

Description

int To Hex Bytes

License

Apache License

Declaration

public static byte[] intToHexBytes(int i) 

Method Source Code

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

public class Main {
    public static byte[] intToHexBytes(int i) {
        byte[] bytes = new byte[8];
        oneByteToHexBytes((byte) ((i >>> 24) & 0xff), bytes, 0);
        oneByteToHexBytes((byte) ((i >>> 16) & 0xff), bytes, 2);
        oneByteToHexBytes((byte) ((i >>> 8) & 0xff), bytes, 4);
        oneByteToHexBytes((byte) (i & 0xff), bytes, 6);
        return bytes;
    }/*w ww.  j a va2 s.  co  m*/

    public static byte[] intToHexBytes(int i, byte[] bytes) {
        oneByteToHexBytes((byte) ((i >>> 24) & 0xff), bytes, 0);
        oneByteToHexBytes((byte) ((i >>> 16) & 0xff), bytes, 2);
        oneByteToHexBytes((byte) ((i >>> 8) & 0xff), bytes, 4);
        oneByteToHexBytes((byte) (i & 0xff), bytes, 6);
        return bytes;
    }

    public static byte[] intToHexBytes(int i, byte[] bytes, int startIdx) {
        oneByteToHexBytes((byte) ((i >>> 24) & 0xff), bytes, startIdx);
        oneByteToHexBytes((byte) ((i >>> 16) & 0xff), bytes, startIdx + 2);
        oneByteToHexBytes((byte) ((i >>> 8) & 0xff), bytes, startIdx + 4);
        oneByteToHexBytes((byte) (i & 0xff), bytes, startIdx + 6);
        return bytes;
    }

    private static byte[] oneByteToHexBytes(byte b, byte[] hexBytes, int startIdx) {
        byte high = (byte) ((b & 0xf0) >>> 4);
        if (high <= 9)
            high += '0';
        else
            high += ('A' - 10);
        hexBytes[startIdx] = high;

        byte low = (byte) (b & 0x0f);
        if (low <= 9)
            low += '0';
        else
            low += ('A' - 10);
        hexBytes[startIdx + 1] = low;

        return hexBytes;
    }
}

Related

  1. intToHex(int val)
  2. intToHex(int val, char delim)
  3. intToHex(int val, StringBuffer sb)
  4. intTohex2(int value)
  5. intToHex8(int value)
  6. intToHexChar(int i)
  7. intToHexChars(int n)
  8. intToHexLE(int val)
  9. intToHexStr(int i, int len)