该编码器将确保任意数量的符号具有相同长度的结果。
public class SymbolEncoder {
private static final int INT_BITS = 32;
public static String SYM_BINARY = "01";
public static String SYM_ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final String _symbols;
private final int _symCount;
private final int _outSize;
/**
* Construct an encoder that will encode numeric values as
* a String of symbols.
* @param _symbols
*/
public SymbolEncoder(String _symbols) {
this._symbols = _symbols;
this._symCount = _symbols.length();
// calculate the number of symbols needed to encode a 32-bit int
this._outSize = calcSymbols(INT_BITS, this._symCount);
}
/**
* Calculate the number of symbols needed to encode.
* @param _bits Number of bits to be encoded.
* @param _symCount Number of symbols to encode.
* @return
*/
private static int calcSymbols(int _bits, int _symCount) {
return (int)(_bits*Math.log(2)/Math.log(_symCount));
}
public String encodeFloat(float _val) {
return encodeInt(Float.floatToIntBits(_val));
}
public String encodeInt(int _val) {
StringBuilder _sb = new StringBuilder();
int _input = _val;
for(int _idx = 0; _idx < this._outSize; _idx++) {
// get the current symbol
int _symbolIdx = Integer.remainderUnsigned(_input, this._symCount);
char _symbol = this._symbols.charAt(_symbolIdx);
_sb.append(_symbol);
// shift the symbol out of the input
_input = _input / this._symCount;
}
return _sb.reverse().toString();
}
}
测试用例:
SymbolEncoder _bEncode = new SymbolEncoder(SymbolEncoder.SYM_BINARY);
LOG.info("MIN_VALUE: {}", _bEncode.encodeInt(Integer.MIN_VALUE));
LOG.info("MAX_VALUE: {}", _bEncode.encodeInt(Integer.MAX_VALUE));
SymbolEncoder _alnEncode = new SymbolEncoder(SymbolEncoder.SYM_ALPHANUM);
LOG.info("MIN_VALUE: {}", _alnEncode.encodeFloat(Float.MIN_VALUE));
LOG.info("Zero: {}", _alnEncode.encodeFloat(0));
LOG.info("MAX_VALUE: {}", _alnEncode.encodeFloat(Float.MAX_VALUE));
结果:
MIN_VALUE: 10000000000000000000000000000000
MAX_VALUE: 01111111111111111111111111111111
MIN_VALUE: 000001
Zero: 000000
MAX_VALUE: ZDK8AN