Java Convert via ByteBuffer toBytes(Number value)

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

Description

Converts primitive arithmetic types to byte array.

License

Apache License

Parameter

Parameter Description
value the number.

Return

the bytes.

Declaration

public static byte[] toBytes(Number value) 

Method Source Code


//package com.java2s;
/*//from   ww  w . j  a v  a 2  s  . c  om
 * Copyright (c) 2010-2018. Axon Framework
 * 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.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Converts primitive arithmetic types to byte array.
     *
     * @param value the number.
     * @return the bytes.
     */
    public static byte[] toBytes(Number value) {
        if (value instanceof Short) {
            return toBytes((Short) value);
        } else if (value instanceof Integer) {
            return toBytes((Integer) value);
        } else if (value instanceof Long) {
            return toBytes((Long) value);
        } else if (value instanceof Float) {
            return toBytes((Float) value);
        } else if (value instanceof Double) {
            return toBytes((Double) value);
        }
        throw new IllegalArgumentException("Cannot convert " + value + " to bytes");
    }

    private static byte[] toBytes(Short value) {
        ByteBuffer buffer = ByteBuffer.allocate(Short.BYTES);
        buffer.putShort(value);
        return buffer.array();
    }

    private static byte[] toBytes(Integer value) {
        ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
        buffer.putInt(value);
        return buffer.array();
    }

    private static byte[] toBytes(Long value) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(value);
        return buffer.array();
    }

    private static byte[] toBytes(Float value) {
        ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES);
        buffer.putFloat(value);
        return buffer.array();
    }

    private static byte[] toBytes(Double value) {
        ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
        buffer.putDouble(value);
        return buffer.array();
    }
}

Related

  1. toBytes(final float val)
  2. toBytes(final UUID uuid)
  3. toBytes(InputStream input)
  4. toBytes(int value)
  5. toBytes(long l)
  6. toBytes(Object obj)
  7. toBytes(String str, boolean wideChar)
  8. toBytes(String value)
  9. toBytes(UUID id)