Java Byte Array Create toBytes(long l)

Here you can find the source of toBytes(long l)

Description

to Bytes

License

Apache License

Declaration

public static byte[] toBytes(long l) 

Method Source Code

//package com.java2s;
/*/*  w  w w. j a  va  2 s .  c  o  m*/
 * JEF - Copyright 2009-2010 Jiyi (mr.jiyi@gmail.com)
 *
 * 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[] toBytes(long l) {
        byte[] b = new byte[8];
        putLong(b, l, 0);
        return b;
    }

    public static byte[] toBytes(int i) {
        byte[] b = new byte[4];
        putInt(b, i, 0);
        return b;
    }

    public static byte[] toBytes(short i) {
        byte[] b = new byte[2];
        putShort(b, i, 0);
        return b;
    }

    public static void putLong(byte[] bb, long x, int offset) {
        bb[offset + 0] = (byte) (x >> 56);
        bb[offset + 1] = (byte) (x >> 48);
        bb[offset + 2] = (byte) (x >> 40);
        bb[offset + 3] = (byte) (x >> 32);
        bb[offset + 4] = (byte) (x >> 24);
        bb[offset + 5] = (byte) (x >> 16);
        bb[offset + 6] = (byte) (x >> 8);
        bb[offset + 7] = (byte) (x >> 0);
    }

    public static void putInt(byte[] bb, int x, int offset) {
        bb[offset + 0] = (byte) (x >> 24);
        bb[offset + 1] = (byte) (x >> 16);
        bb[offset + 2] = (byte) (x >> 8);
        bb[offset + 3] = (byte) (x >> 0);
    }

    public static void putShort(byte b[], short s, int offset) {
        int len = b.length;
        if (offset < len)
            b[offset] = (byte) (s >> 8);
        if (offset + 1 < len)
            b[offset + 1] = (byte) (s >> 0);
    }
}

Related

  1. toBytes(int value)
  2. toBytes(int value, byte[] dest, int destPos)
  3. toBytes(int x, byte[] out)
  4. toBytes(int[] ints)
  5. toBytes(long input)
  6. toBytes(long l, byte[] bytes, int offset, int limit)
  7. toBytes(long lp)
  8. toBytes(long n)
  9. toBytes(long number)