Java Integer to Byte Array intToBytesNoLeadZeroes(int val)

Here you can find the source of intToBytesNoLeadZeroes(int val)

Description

Converts a int value into a byte array.

License

Open Source License

Parameter

Parameter Description
val - int value to convert

Return

value with leading byte that are zeroes striped

Declaration

public static byte[] intToBytesNoLeadZeroes(int val) 

Method Source Code

//package com.java2s;
/*/*  w ww  .j  a v  a  2 s . c o  m*/
 * This file is part of RskJ
 * Copyright (C) 2017 RSK Labs Ltd.
 * (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>)
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * 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
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    /**
     * Converts a int value into a byte array.
     *
     * @param val - int value to convert
     * @return value with leading byte that are zeroes striped
     */
    public static byte[] intToBytesNoLeadZeroes(int val) {

        if (val == 0) {
            return EMPTY_BYTE_ARRAY;
        }

        int lenght = 0;

        int tmpVal = val;
        while (tmpVal != 0) {
            tmpVal = tmpVal >>> 8;
            ++lenght;
        }

        byte[] result = new byte[lenght];

        int index = result.length - 1;
        while (val != 0) {

            result[index] = (byte) (val & 0xFF);
            val = val >>> 8;
            index -= 1;
        }

        return result;
    }
}

Related

  1. intToBytesBigEndian(int n)
  2. IntToBytesLE(final long val)
  3. intToBytesLE(int i, byte[] bytes, int off)
  4. intToBytesLE(int value, byte[] buffer, int offset, int length)
  5. intToBytesLittleEndian(final int i, final byte[] dest, final int offset)
  6. intToBytesSizeOne(int integer)