Java BigDecimal Encode encodePackedBCD(BigDecimal v, int decimals, int length)

Here you can find the source of encodePackedBCD(BigDecimal v, int decimals, int length)

Description

Convert from BigDecimal to packed BCD.

License

Apache License

Parameter

Parameter Description
v BigDecimal object
decimals implied decimals
length length

Return

byte array with packed BCD

Declaration

public static byte[] encodePackedBCD(BigDecimal v, int decimals, int length) 

Method Source Code


//package com.java2s;
/*// ww w  .ja va2s  .co  m
 * Copyright 2009 Arne Vajh?j.
 * 
 * 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.math.BigDecimal;

public class Main {
    /**
     * Convert from BigDecimal to packed BCD. 
     * @param v BigDecimal object
     * @param decimals implied decimals
     * @param length length
     * @return byte array with packed BCD
     */
    public static byte[] encodePackedBCD(BigDecimal v, int decimals, int length) {
        long v2 = v.scaleByPowerOfTen(decimals).longValue();
        byte[] res = new byte[length];
        int low = 12;
        if (v2 < 0) {
            low = 13;
            v2 = -v2;
        }
        int high = (int) (v2 % 10);
        v2 /= 10;
        res[res.length - 1] = (byte) (high << 4 | low);
        for (int i = res.length - 2; i >= 0; i--) {
            low = (int) (v2 % 10);
            v2 /= 10;
            high = (int) (v2 % 10);
            v2 /= 10;
            res[i] = (byte) (high << 4 | low);
        }
        return res;
    }
}

Related

  1. encodeImage(BufferedImage bufferedImage, File file)
  2. encodeRealNumberRange(BigDecimal number, int maxNumDigits, BigDecimal offsetValue)
  3. encodeRealNumberRange(BigDecimal number, int maxNumDigits, BigDecimal offsetValue)