⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 numberencoder.java

📁 中国移动定位引擎的客户端
💻 JAVA
字号:
/**
*
* <p>Title: Smgp协议TLV结构解析</p>
* <p>Description: 数值型编码</p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: 福富软件</p>
* @author chenxin
* @version 1.0 $Date 2007-07-03
*/
package ffcs.lbp.le.message.tlv;

import ffcs.lbp.le.util.LeIO;



/**
 * Encode a <code>java.lang.Number</code> to a byte array. The number encoder
 * is for encoding any optional parameters that are defined as integers.
 * NumberEncoder operates on the {@link java.lang.Number}type and therefore
 * accepts values of Byte, Short, Integer and Long. Encoding and decoding of
 * values using this class will never fail due to a lenght mismatch..the value
 * will always be either zero-padded or truncated down to the appropriate size.
 * 
 * @author Oran Kelly
 * @version $Id: NumberEncoder.java 255 2006-03-09 09:34:37Z orank $
 */
public class NumberEncoder implements Encoder {

    /**
     * Create a new NumberEncoder.
     */
    public NumberEncoder() {
    }

    public void writeTo(Tag tag, Object value, byte[] b, int offset) {

        long longVal = 0;
        long mask = 0;
        Number num;
        try {
            num = (Number) value;
        } catch (ClassCastException x) {
            throw new BadValueTypeException("Value must be of type "
                    + "java.lang.Number");
        }

        if (value instanceof Byte) {
            mask = 0xff;
        } else if (value instanceof Short) {
            mask = 0xffff;
        } else if (value instanceof Integer) {
            mask = 0xffffffff;
        } else {
            mask = 0xffffffffffffffffL;
        }

        longVal = num.longValue() & mask;
        LeIO.longToBytes(longVal, tag.getLength(), b, offset);
    }

    public Object readFrom(Tag tag, byte[] b, int offset, int length) {
        long val = LeIO.bytesToLong(b, offset, length);

        if (length <= 4) {
            return new Integer((int) val);
        } else {
            return new Long(val);
        }
    }

    public int getValueLength(Tag tag, Object value) {
        return tag.getLength();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -