Here you can find the source of toBytes(Number value)
Parameter | Description |
---|---|
value | the number. |
public static byte[] toBytes(Number value)
//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(); } }