ByteBuffer packDecimal() {
        ByteBuffer buffer = ByteBuffer.allocate(type.getTypeSize());
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        int scale = ((ScalarType) type).getScalarScale();
        BigDecimal scaledValue = value.multiply(SCALE_FACTOR[scale]);
        switch (type.getPrimitiveType()) {
            case DECIMAL32:
                buffer.putInt(scaledValue.intValue());
                break;
            case DECIMAL64:
                buffer.putLong(scaledValue.longValue());
                break;
            case DECIMAL128:
            case DECIMALV2:
                // BigInteger::toByteArray returns a big-endian byte[], so copy in reverse order one by one byte.
                byte[] bytes = scaledValue.toBigInteger().toByteArray();
                for (int i = bytes.length - 1; i >= 0; --i) {
                    buffer.put(bytes[i]);
                }
                // pad with sign bits
                byte prefixByte = scaledValue.signum() >= 0 ? (byte) 0 : (byte) 0xff;
                int numPaddingBytes = 16 - bytes.length;
                for (int i = 0; i < numPaddingBytes; ++i) {
                    buffer.put(prefixByte);
                }
                break;
            default:
                Preconditions.checkArgument(false, "Type bust be decimal type");
        }
        buffer.flip();
        return buffer;
    }
@Test
    public void testPackDecimal() {
        BigInteger[] bigIntegers = new BigInteger[] {
                BigInteger.ZERO,
                BigInteger.ONE,
                BigInteger.ONE.shiftLeft(31).subtract(BigInteger.ONE),
                BigInteger.ONE.shiftLeft(31).negate(),
                BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE),
                BigInteger.ONE.shiftLeft(32).negate(),
                BigInteger.ONE.shiftLeft(63).subtract(BigInteger.ONE),
                BigInteger.ONE.shiftLeft(63).negate(),
                BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE),
                BigInteger.ONE.shiftLeft(64).negate(),
                BigInteger.ONE.shiftLeft(126).subtract(BigInteger.ONE),
                BigInteger.ONE.shiftLeft(126).negate(),
        };
        for (BigInteger integer : bigIntegers) {
            BigDecimal decimal = new BigDecimal(integer, 3);
            DecimalLiteral decimalLiteral = new DecimalLiteral(decimal);
            ByteBuffer packed = decimalLiteral.packDecimal();
            int numBytes = packed.limit();
            byte[] bytes = new byte[numBytes];
            packed.get(bytes);
            int i = 0, j = numBytes - 1;
            while (i < j) {
                byte tmp = bytes[j];
                bytes[j] = bytes[i];
                bytes[i] = tmp;
                ++i;
                --j;
            }
            BigInteger expected = new BigInteger(bytes);
            Assert.assertEquals(expected, integer);
        }
    }