为了账号安全,请及时绑定邮箱和手机立即绑定

Java:使用自定义符号在基数之间进行转换

Java:使用自定义符号在基数之间进行转换

缥缈止盈 2021-05-31 13:15:14
我想知道您是否可以使用自己的符号创建自定义基础,而不是使用Integer.parseInt(0-9和A-P.)我在想这样的事情:public class Base {    private String symbols;    public Base(String symbols) {        this.symbols = symbols;    }    // for example: new Base("0123456789"); would represent base 10    public static String convertBases(Base from, Base to, String toConvert) {        // Takes toConvert which is encoded in base "from" and converts it to base "to"    }}我不确定如何实现这一点。有没有人有这个代码?
查看完整描述

2 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

让我们从值类型开始。它包含一个字符串表示和一个 Base 对象。(即,它有一个字符串表示和一个类似解码器的东西)。为什么?因为我们不想传递我们需要查看并“猜测”它们是什么基础的字符串。


public class CustomNumber {

    private final String stringRepresentation;

    private final Base base;

    public CustomNumber(String stringRepresentation, Base base) {

        super();

        this.stringRepresentation = stringRepresentation;

        this.base = base;

    }



    public long decimalValue() {

        return base.toDecimal(stringRepresentation);

    }

    public CustomNumber toBase(Base newBase) {

        long decimalValue = this.decimalValue();

        String stringRep = newBase.fromDecimal(decimalValue);

        return new CustomNumber(stringRep, newBase);

    }

}

然后我们需要定义一个足够广泛的接口来处理任何常规或自定义符号库。我们稍后会在上面构建具体的实现。


public interface Base {

        public long toDecimal(String stringRepresentation);

        public String fromDecimal(long decimalValue);

}

我们都准备好了。在转到自定义字符串符号之前,让我们做一个示例实现以支持标准十进制数字格式:


public class StandardBaseLong implements Base{

    public long toDecimal(String stringRepresentation) {

        return Long.parseLong(stringRepresentation);

    }


    public String fromDecimal(long decimalValue) {

        return Long.toString(decimalValue);

    }

}

现在终于来到自定义字符串库:


public class CustomBase implements Base{

    private String digits;

    public CustomBase(String digits) {

        this.digits = digits;

    }


    public long toDecimal(String stringRepresentation) {

        //Write logic to interpret that string as your base

        return 0L;

    }


    public String fromDecimal(long decimalValue) {

        //Write logic to generate string output in your base format

        return null;

    }

}

现在您有一个框架来处理各种自定义和标准基础。


当然,可能会有更多的定制和改进的功能(更多方便的构造函数、hashCode 和 equals 实现和算术)。但是,它们超出了这个答案的范围。


查看完整回答
反对 回复 2021-06-02
  • 2 回答
  • 0 关注
  • 109 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信