Java Byte Array Create toByteArray(byte arg, int length)

Here you can find the source of toByteArray(byte arg, int length)

Description

to Byte Array

License

Apache License

Declaration

public static byte[] toByteArray(byte arg, int length) 

Method Source Code

//package com.java2s;
/*/*w w  w . j a  va2s. c o m*/
 * Copyright 2012 Sony Computer Science Laboratories, Inc. <info@kadecot.net>
 *
 * Licensed 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 {
    public static byte[] toByteArray(byte arg, int length) {
        byte[] ret = new byte[length];
        byte num = arg;
        for (int i = length - 1; i >= 0; i--) {
            ret[i] = (byte) (num & 0xFF);
            num >>= 8;
        }
        return ret;
    }

    public static byte[] toByteArray(byte arg) {
        return toByteArray(arg, 1);
    }

    public static byte[] toByteArray(short arg, int length) {
        byte[] ret = new byte[length];
        short num = arg;
        for (int i = length - 1; i >= 0; i--) {
            ret[i] = (byte) (num & 0xFF);
            num >>= 8;
        }
        return ret;
    }

    public static byte[] toByteArray(short arg) {
        return toByteArray(arg, 2);
    }

    public static byte[] toByteArray(int arg, int length) {
        byte[] ret = new byte[length];
        int num = arg;
        for (int i = length - 1; i >= 0; i--) {
            ret[i] = (byte) (num & 0xFF);
            num >>= 8;
        }
        return ret;
    }

    public static byte[] toByteArray(int arg) {
        return toByteArray(arg, 4);
    }

    public static byte[] toByteArray(long arg, int length) {
        byte[] ret = new byte[length];
        long num = arg;
        for (int i = length - 1; i >= 0; i--) {
            ret[i] = (byte) (num & 0xFF);
            num >>= 8;
        }
        return ret;
    }

    public static byte[] toByteArray(long arg) {
        return toByteArray(arg, 8);
    }
}

Related

  1. newByteArray(int... bytes)
  2. toByte(char[] bytes, boolean le)
  3. toByteArr(final float value, final boolean lsbIsFirst)
  4. toByteArray(boolean[] array)
  5. toByteArray(boolean[] bits)
  6. toByteArray(byte b)
  7. toByteArray(byte byteArray)
  8. toByteArray(byte num)
  9. toByteArray(byte value)