Android Int to Byte Array Convert getTwoBytes(int i)

Here you can find the source of getTwoBytes(int i)

Description

Gets a two byte array from an integer

License

Open Source License

Parameter

Parameter Description
i the integer

Return

the two bytes

Declaration

public static byte[] getTwoBytes(int i) 

Method Source Code

//package com.java2s;
/*********************************************************************
 *
 *      Copyright (C) 2002 Andrew Khan//from   w  w w  .  ja va  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(byte[] bytes, int offset, int value)
  2. intToBytes(int number)
  3. intToBytes(int number)
  4. toByteArray(int in)
  5. toByteArray(int in, int outSize)
  6. getTwoBytes(int i, byte[] target, int pos)
  7. getFourBytes(int i)
  8. getFourBytes(int i, byte[] target, int pos)
  9. splitInt(int value)