Java Convert via ByteBuffer intToBytesWithLen(int x, int len)

Here you can find the source of intToBytesWithLen(int x, int len)

Description

Write a big-endian integer into the least significant bytes of a byte array.

License

Open Source License

Declaration

public static byte[] intToBytesWithLen(int x, int len) 

Method Source Code


//package com.java2s;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
    /**/* w  ww .j ava2  s .  c o  m*/
     * Write a big-endian integer into the least significant bytes of a byte array.
     */
    public static byte[] intToBytesWithLen(int x, int len) {
        if (len <= 4) {
            return trailingBytes(intToBytes(x), len);
        } else {
            ByteBuffer bb = ByteBuffer.allocate(len);
            bb.position(len - 4);
            bb.putInt(x);
            assert bb.remaining() == 0;
            return bb.array();
        }
    }

    public static byte[] trailingBytes(byte[] bs, int numBytes) {
        return Arrays.copyOfRange(bs, bs.length - numBytes, bs.length);
    }

    public static byte[] intToBytes(int x) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.putInt(x);
        return bb.array();
    }
}

Related

  1. intToBytes(final int x)
  2. intToBytes(int i, byte[] backingStore, int offset)
  3. intToBytes(int n)
  4. intToBytes(int tagId)
  5. intToBytesLE(int value)
  6. long2bytes(long num)
  7. longFromBytes(byte[] array)
  8. longFromBytes(byte[] value)
  9. longTo4ByteArray(long n)