将存储在整数列表(小端)中的二进制表示形式转换为Biginteger [英] Conversion of a binary representation stored in a list of integers (little endian) into a Biginteger

查看:67
本文介绍了将存储在整数列表(小端)中的二进制表示形式转换为Biginteger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数列表,比如说L,其中包含数字的二进制表示形式. 列表L中的每个整数可以为0或1.最低有效位"在左侧(而不是右侧).

I have a list of integers, say L which contains the binary representation of a number. Each integer in the list L can be 0 or 1. The "least significant bit" is on the left (not on the right).

例如:(十进制)961为1000001111,对于558为0111010001.

Example: 1000001111 for the (decimal) number 961, or 0111010001 for 558.

我想将列表转换成Biginteger.

I want to convert the list into a Biginteger.

到目前为止,我已经尝试了以下方法:

I have tried the following so far:

Dim bytes(L.Count - 1) As Byte
For i As Integer = 0 to L.Count - 1 
    bytes(i) = CByte(L(i))
Next

Dim Value As New BigInteger(bytes)

Return Value

但是结果是完全错误的.任何人都可以帮助进行此转换吗? C#的vb.net示例同样完美.

but the result is completely wrong. Can anyone help to make this conversion? c# of vb.net examples are equally perfect.

我也从以下问题中调查了以下内容:

I have also looked into something like the following taken from a question here:

Buffer.BlockCopy(intArray, 0, byteArray, 0, byteArray.Length);

但Biginteger转换仍然没有成功.

but still with no success with the Biginteger conversion.

推荐答案

使用乔恩·斯基特(Jon Skeet)的这段代码将其转换为byte[].

int[] ints = new[] { 1,0,0,0,0,0,1,1,1,1 };
// 1,0,0,... becomes true,false,false,... with this Select
BitArray bits = new BitArray(ints.Select(x => x > 0).ToArray());

byte[] bytes = new byte[(bits.Length + 7) / 8];
bits.CopyTo(bytes, 0);

BigInteger bigInt = new BigInteger(bytes); // 961

如果性能至关重要,则可以通过使用移位构建byte[]来改善性能.但这是(IMO)简洁,易读且(我希望)快速代码保持原样的方法.

If performance is critical, you could probably improve it by building your byte[] using bit shifting. But this is decently (IMO) concise, readable, and (I'd expect) fast code as-is.

558(0,1,1,1,0,1,0,0,0,1)也可以.

这篇关于将存储在整数列表(小端)中的二进制表示形式转换为Biginteger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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