Java Byte Array Create toBytes(int value)

Here you can find the source of toBytes(int value)

Description

Converts an int value to a byte array

License

Apache License

Parameter

Parameter Description
value the value to convert

Return

returns the byte array representing this int value.

Declaration

public static byte[] toBytes(int value) 

Method Source Code

//package com.java2s;
/*/*  w  w  w  .j av  a  2s .co  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Converts an int value to a byte array
     * 
     * @param value
     *        the value to convert
     * @return returns the byte array representing this int value.
     * @since Commons Checksum 1.0
     */
    public static byte[] toBytes(int value) {
        byte[] b = new byte[4];
        for (int i = 3; i > 0; i--) {
            b[i] = (byte) (value);
            value >>>= 8;
        }
        b[0] = (byte) (value);
        return b;
    }

    /**
     * Converts a long value to a byte array
     * 
     * @param value
     *            the value to convert
     * @param size
     *            the size of byte array representing this long value.
     * @return returns the byte array representing this long value.
     * @since Commons Checksum 1.0
     */
    public static byte[] toBytes(long value, int size) {
        if (size > 8 || size < 1) {
            size = 8;
        }
        byte[] b = new byte[size];
        for (int i = (size - 1); i > 0; i--) {
            b[i] = (byte) (value);
            value >>>= 8;
        }
        b[0] = (byte) (value);
        return b;
    }
}

Related

  1. toBytes(int is)
  2. toBytes(int megabytes)
  3. toBytes(int n)
  4. toBytes(int n)
  5. toBytes(int val)
  6. toBytes(int value)
  7. toBytes(int value)
  8. toBytes(int value)
  9. toBytes(int value)