【问题标题】:string to bigint in dart飞镖中的字符串到bigint
【发布时间】:2021-12-27 06:01:38
【问题描述】:

我想通过 modPow 加密 String “this is a simple string”,但是我在 BigInt API 中没有找到方法,如何在 Dart 中将 String 转换为 BigInt?

String original = "this is a simple string";

BigInt modulusInt = BigInt.parse(n, radix: 16);
BigInt exponentInt = BigInt.parse(e, radix: 16);

现在当原始可以转换为 BigInt 时,我可以使用 modPow

【问题讨论】:

    标签: dart bigint


    【解决方案1】:

    编辑添加一些澄清和 cmets 到代码

    首先您必须定义一个从StringBigInt 的映射。换句话说,您必须使用编码方案将字符编码为数字。 dart 中的String 类提供了一个getter codeUnits 来将字符串转换为UTF-16 字符编码的List,因此如果你想采用UTF-16 编码,你可以利用这个getter 方法,您可以使用String 的工厂构造函数fromCharCodes 将列表转回字符串:

    BigInt uint16SeqToBigInt(List<int> seq){
      var ret = BigInt.from(0);
      int offset = 0;
      for(int i in seq){
        // Shift the UTF-16 code of each character to "slots" of 16-bit size
        ret += (BigInt.from(i)) << offset;
        offset += 16;
      }
      return ret;
    }
    
    List<int> bigIntToUint16Seq(BigInt val){
      final ret = <int>[];
      int cur;
      while(true){
        // 0xFFFF is a bit mask to extract the lower 16-bit value from val
        cur = (val & BigInt.from(0xFFFF)).toInt();
        if(cur != 0){
          ret.add(cur);
          // The last 16 bits is interpreted, now discard them
          val = val >> 16;
        }else{
          break;
        }
      }
      
      return ret;
    }
    
    void main() {
      String original = "this is a simple string";
      final utf16BigInt = uint16SeqToBigInt(original.codeUnits);
      final decoded = String.fromCharCodes(bigIntToUint16Seq(utf16BigInt));
      print(decoded);
      // "this is a simple string"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 2023-01-10
      • 2022-11-24
      • 1970-01-01
      • 2019-04-13
      • 2020-09-07
      • 1970-01-01
      相关资源
      最近更新 更多