int To Bytes via ByteBuffer - Java java.nio

Java examples for java.nio:ByteBuffer Int

Description

int To Bytes via ByteBuffer

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] argv) throws Exception {
        int value = 2;
        System.out.println(java.util.Arrays.toString(intToBytes(value)));
    }//from  w  ww .  j  a v a 2s .c  o  m

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

    public static String toString(byte[] bytes, int offset, int length)
            throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        System.out.println("bytes.length=" + bytes.length + " offset="
                + offset + " length=" + length);
        bos.write(bytes, offset, length);
        String str = bos.toString();
        bos.close();

        return str;
    }
}

Related Tutorials