Android Int to Byte Array Convert getTwoBytes(int i, byte[] target, int pos)

Here you can find the source of getTwoBytes(int i, byte[] target, int pos)

Description

Converts an integer into two bytes, and places it in the array at the specified position

License

Open Source License

Parameter

Parameter Description
target the array to place the byte data into
pos the position at which to place the data
i the integer value to convert

Declaration

public static void getTwoBytes(int i, byte[] target, int pos) 

Method Source Code

//package com.java2s;
/*********************************************************************
 *
 *      Copyright (C) 2002 Andrew Khan/*from ww  w.  ja  v  a  2  s  .  co  m*/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 ***************************************************************************/

public class Main {
    /**
     * Gets a two byte array from an integer
     *
     * @param i the integer
     * @return the two bytes
     */
    public static byte[] getTwoBytes(int i) {
        byte[] bytes = new byte[2];

        bytes[0] = (byte) (i & 0xff);
        bytes[1] = (byte) ((i & 0xff00) >> 8);

        return bytes;
    }

    /**
     * Converts an integer into two bytes, and places it in the array at the
     * specified position
     *
     * @param target the array to place the byte data into
     * @param pos the position at which to place the data
     * @param i the integer value to convert
     */
    public static void getTwoBytes(int i, byte[] target, int pos) {
        target[pos] = (byte) (i & 0xff);
        target[pos + 1] = (byte) ((i & 0xff00) >> 8);
    }
}

Related

  1. intToBytes(int number)
  2. intToBytes(int number)
  3. toByteArray(int in)
  4. toByteArray(int in, int outSize)
  5. getTwoBytes(int i)
  6. getFourBytes(int i)
  7. getFourBytes(int i, byte[] target, int pos)
  8. splitInt(int value)
  9. int2Byte(int value)