Java Integer to Byte Array intToBytes(int i)

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

Description

int To Bytes

License

Open Source License

Declaration

public static byte[] intToBytes(int i) 

Method Source Code

//package com.java2s;
/**/*from w  w w .  jav  a2s  . c o  m*/
 * Copyright 2008 ManyBrain, Inc. All Rights Reserved. Us is subject to
 * license Terms.
 * <p/>
 * Author: Paul Tyma
 * <p/>
 * This file is part of ManyBrain Memcached Java client.
 * <p/>
 * The ManyBrain Memcached Java client is free software; you can
 * redistribute it and/or modify
 * it under the terms of the Lesser GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * <p/>
 * This program 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 Lesser GNU
 * General Public License for more details.
 * <p/>
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

public class Main {
    public static byte[] intToBytes(int i) {
        boolean neg = false;
        int digs = 1;
        if (i < 0) {
            digs++;
            neg = true;
            i = -i;
        }

        int base10 = 10;
        while (true) {
            if (base10 > i)
                break;
            base10 *= 10;
            digs++;
        }

        byte[] bytes = new byte[digs];

        for (int g = digs - 1; g >= 0; --g) {
            bytes[g] = (byte) ((i % 10) + '0');
            i = i / 10;
        }

        if (neg)
            bytes[0] = '-';
        return bytes;
    }

    public static int intToBytes(int i, byte[] bytes, int off) {

        int digs = 1;
        int base10 = 10;
        while (i > base10) {
            base10 *= 10;
            digs++;
        }

        off = off + digs;
        digs = off;

        do {
            bytes[--off] = (byte) ((i % 10) + '0');
            i = i / 10;
        } while (i != 0);
        return digs;
    }
}

Related

  1. intToBytes(final int value)
  2. intToBytes(int a, byte[] b, int bo)
  3. intToBytes(int i)
  4. intToBytes(int i)
  5. intToBytes(int i)
  6. intToBytes(int i)
  7. intToBytes(int i)
  8. intToBytes(int i)
  9. intToBytes(int i)