65.9K
CodeProject 正在变化。 阅读更多。
Home

LINT:大整数对象库

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.59/5 (19投票s)

2005年12月9日

CPOL

2分钟阅读

viewsIcon

95002

downloadIcon

665

Lint 是一个带符号的大整数数据类型类库。

引言

Lint 是一个带符号的大整数数据类型类库,它支持其他固有整数数据类型的所有可用数学运算符。精度不是像其他可用库中那样是任意的。相反,组成 lint 变量的位数取决于头文件中声明的 #define 指令的值。

背景

那么,为什么要另一个大整数库呢?原因有以下几点:

  • 我想要一个支持所有可能的重载运算符的类,这样我就可以像使用 intlong 等固有数据类型一样使用 lint。我能找到的任何免费实现似乎都不支持 ALL 可重载运算符。
  • 我想要一个专门为 Visual C++ 和基于 IA-32 的 PC 架构创建的类。我不想为了跨编译器和跨平台兼容性而牺牲执行速度的库。 我想要一个可以使用内联汇编代码优化的库。
  • 我想要一个方法尽可能快速和高效的类。任意精度逻辑和浮点逻辑会带来性能损失。此库是高效的,因为精度不是任意的,并且所有操作都严格基于整数。 这样,给定已知的数据类型和大小,我可以编写高度优化的汇编例程。

Using the Code

一旦你在你的源码中包含头文件,使用 lint 类似于在 C++ 中使用任何其他数值数据类型。 几个值得注意的例外是在声明、赋值和输出中。

#include "lint.h"
#include <stdio.h>

int main() {
    lint a = 1234;          // value assignment of a literal
    lint b = -5678;         // a lint is a signed integer data type
    lint c = a;             // assignment to another lint value
    lint d = "457639857304951675093650987359087";   	// use a string for those 
						// really BIG numbers
    lint e = "-563857365015613047563";	     // this works for negative values too
    
    lint x, y, z;
    x = d*e+a*b;            // math shouldn't be a problem.
    y = x/(e*e);
    
    // assignment to zero is the only ambiguous operation 
    // that you need to be specific on.
    z = (signed long)0;                                

    // the class allocates its own buffer to print a 
    // character representation of its value.
    // By default, it prints in base 10
    printf( "y base 10 = %s\n", z.value() );
    
    // You can print in another radix though - anything from 2 to 36
    printf( "y base 16 = %s\n", z.value(16) );
    printf( "y base 2 = %s\n", z.value(2) );
    
    // Internally, the memory for a lint is laid out going from 
    // MSB to LSB in an array of 32-bit DWORDs.
    // [2047th bit ... 1024th bit ... 0th bit]
    
    // If you need more or less than 2048 bit numbers, open lint.h
    // and redefine LINT_LENGTH
    
    // Lastly, the function call operator allows direct referential 
    // access to the DWORDs that comprise
    // a lint value.
    y(0) = 0x12345678;                  	// This sets the Most Significant 
					// DWORD to 0x12345678
    long my_bit_field = y(LAST_DWORD);  	// LAST_DWORD is a constant defined 
					// in the header file
    
    return 0;
}

关注点

实现条件测试是一个真正的难题。我的实现有效,但我认为必须有更好的方法来做到这一点。 我还想对库做一些额外的事情。

  • 可能使用 FFT、Barrett 或任何其他算法实现更快的乘法和除法算法。
  • 添加使用 2 到 36 之间的任何基数的字符串(而不仅仅是 10 进制)赋值的能力。
  • 利用 MMX 和 XMM 寄存器实现更快的内联汇编。

历史

首次发布 2005 年 12 月 4 日 作者:Jeremy A. Wilson  
更新 2005 年 12 月 6 日 作者:Jeremy A. Wilson 发现我的比较运算符使用了错误的汇编指令,如果在一个 DWORD 中设置了 MSB 而在另一个 DWORD 中没有设置,则无法正确报告。
更新 2005 年 12 月 9 日 作者:Jeremy A. Wilson 在进一步审查我 12 月 6 日的修复程序后,我意识到我仍然没有正确修复它。 现在我修好了。 我还运行了一整套比较。
© . All rights reserved.