Java Integer to Byte Array intToBytes(int i)

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

Description

This function converts a integer to its corresponding byte array format.

License

Open Source License

Parameter

Parameter Description
i The integer to be converted.

Return

The corresponding byte array.

Declaration

static public byte[] intToBytes(int i) 

Method Source Code

//package com.java2s;
/************************************************************************
 * Copyright (c) Crater Dog Technologies(TM).  All Rights Reserved.     *
 ************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.        *
 *                                                                      *
 * This code is free software; you can redistribute it and/or modify it *
 * under the terms of The MIT License (MIT), as published by the Open   *
 * Source Initiative. (See http://opensource.org/licenses/MIT)          *
 ************************************************************************/

public class Main {
    /**/*w  w  w .j a  v  a2 s . c  om*/
     * This function converts a integer to its corresponding byte array format.
     *
     * @param i The integer to be converted.
     * @return The corresponding byte array.
     */
    static public byte[] intToBytes(int i) {
        byte[] buffer = new byte[4];
        intToBytes(i, buffer, 0);
        return buffer;
    }

    /**
     * This function converts a integer into its corresponding byte format and inserts
     * it into the specified buffer.
     *
     * @param i The integer to be converted.
     * @param buffer The byte array.
     * @return The number of bytes inserted.
     */
    static public int intToBytes(int i, byte[] buffer) {
        return intToBytes(i, buffer, 0);
    }

    /**
     * This function converts a integer into its corresponding byte format and inserts
     * it into the specified buffer at the specified index.
     *
     * @param i The integer to be converted.
     * @param buffer The byte array.
     * @param index The index in the array to begin inserting bytes.
     * @return The number of bytes inserted.
     */
    static public int intToBytes(int i, byte[] buffer, int index) {
        int length = buffer.length - index;
        if (length > 4)
            length = 4;
        for (int j = 0; j < length; j++) {
            buffer[index + length - j - 1] = (byte) (i >> (j * 8));
        }
        return length;
    }
}

Related

  1. intToBytes(int i)
  2. intToBytes(int i)
  3. intToBytes(int i)
  4. intToBytes(int i)
  5. intToBytes(int i)
  6. IntToBytes(int i)
  7. intToBytes(int i, byte[] data, int[] offset)
  8. intToBytes(int i_)
  9. intToBytes(int intValue)