Android Int to Byte Array Convert toBytes(int integer, byte[] output, int offset)

Here you can find the source of toBytes(int integer, byte[] output, int offset)

Description

to Bytes

License

Apache License

Declaration

public static void toBytes(int integer, byte[] output, int offset) 

Method Source Code

//package com.java2s;
/**/*  w w w  . j  a  v  a 2s.c  om*/
 * Source obtained from crypto-gwt. Apache 2 License.
 * https://code.google.com/p/crypto-gwt/source/browse/crypto-gwt/src/main/java/com/googlecode/
 * cryptogwt/util/ByteArrayUtils.java
 */

public class Main {
    public static byte[] toBytes(int integer) {
        byte[] result = new byte[4];
        toBytes(integer, result, 0);
        return result;
    }

    public static void toBytes(int integer, byte[] output, int offset) {
        assert output.length - offset >= 4;
        int i = offset;
        output[i++] = (byte) (integer >>> 24);
        output[i++] = (byte) (integer >>> 16);
        output[i++] = (byte) (integer >>> 8);
        output[i++] = (byte) (integer & 0xff);
    }

    public static byte[] toBytes(int... integer) {
        byte[] result = new byte[integer.length * 4];
        int offset = 0;
        for (int i = 0; i < integer.length; i++) {
            toBytes(integer[i], result, offset);
            offset += 4;
        }
        return result;
    }

    public static byte[] toBytes(String s) {
        return toBytes(s.toCharArray());
    }

    public static byte[] toBytes(char[] chars) {
        byte[] result = new byte[chars.length];
        int i = 0;
        for (char c : chars) {
            result[i++] = (byte) c;
        }
        return result;
    }

    public static byte[] toBytes(long longValue) {
        return new byte[] { (byte) (longValue >>> 56),
                (byte) (longValue >>> 48), (byte) (longValue >>> 40),
                (byte) (longValue >>> 32), (byte) (longValue >>> 24),
                (byte) (longValue >>> 16), (byte) (longValue >>> 8),
                (byte) (longValue & 0xff) };
    }
}

Related

  1. ints2bytesBE(int[] val)
  2. ints2bytesLE(int[] val)
  3. intsToBytes(int[] values)
  4. getAs_uint16_NetOrder(int theNumber)
  5. getAs_uint32_NetOrder(int theNumber)
  6. int2ByteArray(int num)
  7. int2ByteArrayBigEndian(int num)
  8. int2ByteArrayLittleEndian(int num)