Java Byte Array Create toByteArray(byte value)

Here you can find the source of toByteArray(byte value)

Description

to Byte Array

License

Apache License

Declaration

public static byte[] toByteArray(byte value) 

Method Source Code

//package com.java2s;
/*//from ww  w.  j a  v  a 2s . c o  m
 * #%L
 * ch-commons-util
 * %%
 * Copyright (C) 2012 Cloudhopper by Twitter
 * %%
 * 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.
 * #L%
 */

public class Main {
    public static byte[] toByteArray(byte value) {
        return new byte[] { value };
    }

    public static byte[] toByteArray(short value) {
        byte[] buf = new byte[2];
        buf[1] = (byte) (value & 0xFF);
        buf[0] = (byte) ((value >>> 8) & 0xFF);
        return buf;
    }

    public static byte[] toByteArray(int value) {
        byte[] buf = new byte[4];
        buf[3] = (byte) (value & 0xFF);
        buf[2] = (byte) ((value >>> 8) & 0xFF);
        buf[1] = (byte) ((value >>> 16) & 0xFF);
        buf[0] = (byte) ((value >>> 24) & 0xFF);
        return buf;
    }

    public static byte[] toByteArray(long value) {
        byte[] buf = new byte[8];
        buf[7] = (byte) (value & 0xFF);
        buf[6] = (byte) ((value >>> 8) & 0xFF);
        buf[5] = (byte) ((value >>> 16) & 0xFF);
        buf[4] = (byte) ((value >>> 24) & 0xFF);
        buf[3] = (byte) ((value >>> 32) & 0xFF);
        buf[2] = (byte) ((value >>> 40) & 0xFF);
        buf[1] = (byte) ((value >>> 48) & 0xFF);
        buf[0] = (byte) ((value >>> 56) & 0xFF);
        return buf;
    }
}

Related

  1. toByteArray(boolean[] bits)
  2. toByteArray(byte arg, int length)
  3. toByteArray(byte b)
  4. toByteArray(byte byteArray)
  5. toByteArray(byte num)
  6. toByteArray(char c)
  7. toByteArray(char[] charArray)
  8. toByteArray(char[] chars)
  9. toByteArray(char[] chars)