即时通讯试图实现转移到bigints。 BigInt由字节数组表示,该字节数组应解释为二进制补码中的单个整数N位。所以我想做这样的事情:
示例数组bigint:
{0xFE,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}将代表整数0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE(-2)N = 128位。
typedef unsigned char * BigInt;
当我尝试创建我的bigint时遇到错误
#include <stdlib.h>
void bi_init (int nbits)
{
nbytes = (nbits/8);
}
BigInt bi_new (int val)
{
BigInt new = (BigInt)malloc(nbytes*sizeof(unsigned char));
new=val --> problem, can someone give me a hint on how can i implement this array?
return novo;
}
最佳答案
typedef unsigned char *BigInt;
BigInt *new = (BigInt)malloc(nbytes*sizeof(unsigned char));
您将
new
声明为unsigned char**
,这是指针的一级太多(并且您不应该在C中强制转换malloc
的结果)。假设
novo
和new
是相同的变量,并且该帖子仅翻译了一次,novo = val
用传入的
val
覆盖刚分配的地址。要用
val
字节填充分配的缓冲区,int i = 0;
// make it unsigned, so that right-shifting works correctly
unsigned int u_val = val;
while(u_val) {
new[i++] = u_val&0xFF;
u_val >>= 8;
}
然后仍然存在问题
nbytes = (nbits/8);
如果
nbits
不是8的倍数,则分配的内存太少nbytes = (nbits+7)/8;
关于c - 创建一个大整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12572051/