Here you can find the source of intToBytesWithLen(int x, int len)
public static byte[] intToBytesWithLen(int x, int len)
//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(); } }