Java ByteOrder toInt16ByteArray(final int val, final ByteOrder outOrder, final byte[] buf, final int off)

Here you can find the source of toInt16ByteArray(final int val, final ByteOrder outOrder, final byte[] buf, final int off)

Description

to Int Byte Array

License

Apache License

Declaration

public static final int toInt16ByteArray(final int val, final ByteOrder outOrder, final byte[] buf,
            final int off) throws NumberFormatException 

Method Source Code

//package com.java2s;
/*// ww w.  j  a va 2s . co m
 * Copyright 2013 Lyor Goldstein
 * 
 * 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.
 */

import java.nio.ByteOrder;

public class Main {
    public static final int toInt16ByteArray(final int val, final ByteOrder outOrder, final byte[] buf,
            final int off) throws NumberFormatException {
        if (null == outOrder)
            throw new NumberFormatException("toInt16ByteArray(" + val + ") no order specified");

        final boolean isBigEndian = ByteOrder.BIG_ENDIAN.equals(outOrder);
        buf[off] = (byte) ((isBigEndian ? (val >> 8) : val) & 0x00FF);
        buf[off + 1] = (byte) ((isBigEndian ? val : (val >> 8)) & 0x00FF);
        return 2;
    }

    public static final int toInt16ByteArray(final int val, final ByteOrder outOrder, final byte[] buf)
            throws NumberFormatException {
        return toInt16ByteArray(val, outOrder, buf, 0);
    }

    public static final byte[] toInt16ByteArray(final int val, final ByteOrder outOrder)
            throws NumberFormatException {
        final byte[] data = new byte[2];
        final int eLen = toInt16ByteArray(val, outOrder, data);
        if (eLen != data.length)
            throw new NumberFormatException("toInt16ByteArray(" + val + ")[" + outOrder
                    + "] unexpected used length: expected=" + data.length + "/got=" + eLen);
        return data;
    }
}

Related

  1. setLong(byte[] bytes, int start, int end, long value, ByteOrder byteOrder)
  2. toBytes(int value, ByteOrder order)
  3. toDoubleByteArray(double val, ByteOrder outOrder, byte[] buf, int off)
  4. toFloatByteArray(float val, ByteOrder outOrder, byte[] buf, int off)
  5. toInt(byte[] bytes, ByteOrder order)
  6. toInt64ByteArray(final long val, final ByteOrder outOrder, final byte[] buf)