手动打印一个N字节的整数 [英] manually printing a N-byte integer

查看:231
本文介绍了手动打印一个N字节的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是可扩展算法,用于手动打印N二进制数字整数 ,其值不适合 long long 。我知道 printf 和朋友,以及< iostream> (很可能捎带在< cstdio> 有标准类型的内置函数,但我想为N个字节组成的整数。

What is a scalable algorithm to print an N-binary-digit integer manually whose value does not fit in long long. I know printf and friends, along with <iostream> (which most likely piggy-backs on <cstdio> have this builtin for standard types, but I'd like to do it for an integer composed of N bytes.

我已经考虑过这个和谷歌有一点,但它总是归结为使用一个预先存在的bigint libirary像GMP(一个我不熟悉的代码库)或使用printf或最有帮助的这是困难的。

I have thought about this and googled a bit, but it always comes down to using a pre-existing bigint libirary like GMP (a codebase I am not at all familiar with) or "use printf" or the most helpful "this is difficult".

整数基本上是:

template<size_t N>
class Integer{
...
private:
    int8_t first;
    uint8_t rest[N-1];
}

因此重新解释 Integer< 4> 一个 int32_t 。我想扩展到N> 8。效率现在不是我的关注,也不是字节序(这是为x86) p>

so reinterpreting an Integer<4>'s bytes would get you an int32_t. I'd like to scale this to N>8. Efficiency is not really my concern at the moment. Neither is endianness (this is for x86).

推荐答案

步骤1:以字符串格式定义包含2的幂的查找表:

Step 1: Define a lookup table containing powers of two in string format:

const char * const powers_of_two[] = {"1", "2", "4", "8", "16", "32", "64", ...};

步骤2:编写一个以字符串格式添加两个数字的函数。

Step 2: Write a function that adds two numbers in string format.

步骤3:迭代数字中的位并添加对应于1位的所有字符串。

Step 3: Iterate through the bits in your number and add all the strings corresponding to the 1 bits.

步骤4:打印结果。

我自己使用这种方法来打印非常大的浮点数,它对我来说很好。

I used this approach myself for printing very large floating point numbers, and it worked fine for me.

这篇关于手动打印一个N字节的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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