Java Convert via ByteBuffer toBytes(BigDecimal number, int byteLength)

Here you can find the source of toBytes(BigDecimal number, int byteLength)

Description

to Bytes

License

Open Source License

Declaration

public static byte[] toBytes(BigDecimal number, int byteLength) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
    public static byte[] toBytes(Number number, int byteLength) {
        if (byteLength <= Long.BYTES) {
            ByteBuffer buffer = ByteBuffer.allocate(byteLength);
            buffer.put(Arrays.copyOfRange(ByteBuffer.allocate(Long.BYTES).putLong(number.longValue()).array(),
                    Long.BYTES - byteLength, Long.BYTES));
            return buffer.array();
        } else {//  w  w  w  .j  av a  2  s .  c  o  m
            throw new IllegalArgumentException("length is larger than long bytes");
        }
    }

    public static byte[] toBytes(BigDecimal number, int byteLength) {
        return toBytes(number.unscaledValue(), byteLength);
    }

    public static byte[] toBytes(BigInteger number, int byteLength) {
        ByteBuffer buffer = ByteBuffer.allocate(byteLength);
        byte[] bytes = number.toByteArray();
        buffer.position(byteLength - bytes.length);
        buffer.put(bytes);
        return buffer.array();
    }
}

Related

  1. toByteArray(UUID uniqueId)
  2. toByteArray2(String filename)
  3. toByteArray3(String filename)
  4. toByteArrayFromInt(int intValue, boolean shortSize)
  5. toByteArrayFromLong(long longValue)
  6. toBytes(char[] ch)
  7. toBytes(char[] chars)
  8. toBytes(char[] string)
  9. toBytes(final float val)