BigInt实现-将字符串转换为以unsigned int形式存储的二进制表示形式 [英] BigInt implementation - converting a string to binary representatio stored as unsigned int

查看:55
本文介绍了BigInt实现-将字符串转换为以unsigned int形式存储的二进制表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++实现BigInt实现,并且很难弄清楚如何创建从(到)字符串的转换器(C字符串现在就足够了).

I'm doing a BigInt implementation in C++ and I'm having a hard time figuring out how to create a converter from (and to) string (C string would suffice for now).

我将数字实现为无符号int数组(因此基本上将位块彼此相邻放置).我只是不知道如何将字符串转换为这种表示形式.

I implement the number as an array of unsigned int (so basically putting blocks of bits next to each other). I just can't figure out how to convert a string to this representation.

例如,如果usigned int为32b,而我得到的字符串为"4294967296"或"5000000000",或者基本上大于32b int可以容纳的值,我如何将其正确转换为适当的二进制表示形式?

For example if usigned int would be 32b and i'd get a string of "4294967296", or "5000000000" or basically anything larger than what a 32b int can hold, how would I properly convert it to appropriate binary representation?

我知道我缺少明显的东西,我只是想向正确的方向发展.感谢您的帮助,也很抱歉提出这样一个愚蠢的问题!

I know I'm missing something obvious, and I'm only asking for a push to the right direction. Thanks for help and sorry for asking such a silly question!

推荐答案

一种方法(不一定是最有效的方法)是实现通常的算术运算符,然后执行以下操作:

Well one way (not necessarily the most efficient) is to implement the usual arithmetic operators and then just do the following:

// (pseudo-code)
// String to BigInt

String s = ...;
BigInt x = 0;

while (!s.empty())
{
    x *= 10;
    x += s[0] - '0';
    s.pop_front();
}

Output(x);

// (pseudo-code)
// BigInt to String

BigInt x = ...;
String s;

while (x > 0)
{
    s += '0' + x % 10;
    x /= 10;
}

Reverse(s);
Output(s);

如果您想做一些比您更棘手的事情,可以尝试以下操作:

If you wanted to do something trickier than you could try the following:

  1. 如果输入I是<100以上使用方法.
  2. 按位长* 3/10估算I的D位数字.
  3. Mod并除以因子F = 10 ^(D/2),得到I = X * F + Y;
  4. 使用I = X和I = Y递归执行

这篇关于BigInt实现-将字符串转换为以unsigned int形式存储的二进制表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆