Java Convert via ByteBuffer toByteArray(int value)

Here you can find the source of toByteArray(int value)

Description

Returns a big-endian representation of value in a 4-element byte array; equivalent to ByteBuffer.allocate(4).putInt(value).array() .

License

Apache License

Declaration

private static byte[] toByteArray(int value) 

Method Source Code

//package com.java2s;
/*/* w  w  w.j a  v  a  2 s .  c  o  m*/
 * Copyright 2009 Thomas Bocek
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

public class Main {
    /**
     * Returns a big-endian representation of {@code value} in a 4-element byte array; equivalent to
     * {@code ByteBuffer.allocate(4).putInt(value).array()} . For example, the input value {@code 0x12131415} would
     * yield the byte array {@code 0x12, 0x13, 0x14, 0x15} .
     * <p>
     * If you need to convert and concatenate several values (possibly even of different types), use a shared
     * {@link java.nio.ByteBuffer} instance, or use {@link com.google.common.io.ByteStreams#newDataOutput()} to get a
     * growable buffer.
     */
    private static byte[] toByteArray(int value) {
        return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value };
    }
}

Related

  1. toByteArray(float[] floatArray)
  2. toByteArray(InputStream input, boolean nioCopy)
  3. toByteArray(int i)
  4. toByteArray(int integer)
  5. toByteArray(int value)
  6. toByteArray(int[] data, boolean bigEndian)
  7. toByteArray(int[] intArray)
  8. toByteArray(long[] data)
  9. ToByteArray(long[] data)