代码之家  ›  专栏  ›  技术社区  ›  Martin

将字节数组转换为一个十进制数字作为字符串

  •  9
  • Martin  · 技术社区  · 15 年前

    我正在尝试编写一个函数,它将一个任意大的字节数组(大于64位)转换成一个十进制数字,用C表示为字符串,但我根本不知道该怎么做。

    例如以下代码…

    Console.WriteLine(ConvertToString(
      new byte[]
      { 
        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 
        0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00
      }));
    

    …应该打印出来

    22774453838368691933757882222884355840
    

    我不想使用像 biginteger 因为我希望它简单,并且喜欢理解它是如何工作的。

    4 回复  |  直到 15 年前
        1
  •  4
  •   Simon Buchan    15 年前

    根据@wilheim的回答:

    static string BytesToString(byte[] data) {
        // Minimum length 1.
        if (data.Length == 0) return "0";
    
        // length <= digits.Length.
        var digits = new byte[(data.Length * 0x00026882/* (int)(Math.Log(2, 10) * 0x80000) */ + 0xFFFF) >> 16];
        int length = 1;
    
        // For each byte:
        for (int j = 0; j != data.Length; ++j) {
            // digits = digits * 256 + data[j].
            int i, carry = data[j];
            for (i = 0; i < length || carry != 0; ++i) {
                int value = digits[i] * 256 + carry;
                carry = Math.DivRem(value, 10, out value);
                digits[i] = (byte)value;
            }
            // digits got longer.
            if (i > length) length = i;
        }
    
        // Return string.
        var result = new StringBuilder(length);
        while (0 != length) result.Append((char)('0' + digits[--length]));
        return result.ToString();
    }
    
        2
  •  6
  •   Wilhelm    15 年前

    一些指导方针:

    1. 您需要将数字的位数保存在一个矩阵中,每个数字有一个空格。矩阵开始为空。
    2. 然后需要一个矩阵来保存矩阵的乘法。它也是空的。
    3. 现在,对于每个字节,您都有:
      1. 首先将当前数字矩阵的每个数字乘以256,将10个模数保存在相应的临时数字中,并将除以10的数字相加到下一个数字乘法中。
      2. 将临时乘法矩阵赋给当前数字矩阵。
      3. 然后将字节添加到第一个数字。
      4. 更正当前矩阵,只保存每个索引中的10个模数,并将除以10的值传递给下一个索引。
    4. 然后需要将每个数字连接到一个字符串中。
    5. 返回字符串。

    不要忘记根据需要扩展每个矩阵,或者根据传递的字节数确定所需的最大大小。

    编辑,示例如下第三步:

    值=[0xAA,0xBB] 初始电流=[] 初始温度=[]

    用0xAA

    1. 没有什么可以增加的。
    2. 工作分配无变化。
    3. 我们在current:current=[170]的第一个值中添加0xAA。
    4. 我们校正电流以仅保存模量,并将除以10的值传递给下一个值:
      1. 第1位:电流=[0]通过17。
      2. 第2位:电流=[0,7]通过1。
      3. 第3位:current=[0,7,1]没有要传递的值,因此进程结束。

    现在用0xBB

    1. 乘以256,保存在temp中并更正,对每个数字执行以下操作:
      1. 第1位:温度=[0],0保存到下一位。
      2. 第2位:校正前温度=[0,1792],校正后温度=[0,2],179通过。
      3. 第3位:校正前temp=[0,2,1*256+179=435],校正后temp=[0,2,5],43通过。
      4. 第4位:temp=[0,2,5,43]之前,temp=[0,2,5,3],3之后通过
      5. 第5位:temp=[0,2,5,3,4]校正前后,没有要保存的数字,所以乘法结束。
    2. 辅助温度对电流:电流=[0,2,5,3,4];温度=[]
    3. 将当前值添加到第一位:current=[187,2,5,3,4]
    4. 更正值:
      1. 第1位:电流=[7,2,5,3,4],18通。
      2. 第2位:电流=[7,0,5,3,4],2通。
      3. 第3位:current=[7,0,7,3,4],没有要传递的内容,所以加法结束。

    现在我们只需要连接结果43707。

        3
  •  1
  •   Pratik Deoghare    15 年前

    你想了解工作原理,看看 超级酷 C# BigInteger Class @ CodeProject .

    此外,我已经将该类剥离为这个问题的基本要素。可以进一步优化。:)

    尝试复制并粘贴以下代码,它可以工作!!

    using System;
    
    public class BigInteger
    {
        // maximum length of the BigInteger in uint (4 bytes)
        // change this to suit the required level of precision.
    
        private const int maxLength = 70;
    
    
        private uint[] data = null;             // stores bytes from the Big Integer
        public int dataLength;                 // number of actual chars used
    
    
        public BigInteger()
        {
            data = new uint[maxLength];
            dataLength = 1;
        }
    
        public BigInteger(long value)
        {
            data = new uint[maxLength];
            long tempVal = value;
    
            dataLength = 0;
            while (value != 0 && dataLength < maxLength)
            {
                data[dataLength] = (uint)(value & 0xFFFFFFFF);
                value >>= 32;
                dataLength++;
            }
    
            if (tempVal > 0)         // overflow check for +ve value
            {
                if (value != 0 || (data[maxLength - 1] & 0x80000000) != 0)
                    throw (new ArithmeticException("Positive overflow in constructor."));
            }
            else if (tempVal < 0)    // underflow check for -ve value
            {
                if (value != -1 || (data[dataLength - 1] & 0x80000000) == 0)
                    throw (new ArithmeticException("Negative underflow in constructor."));
            }
    
            if (dataLength == 0)
                dataLength = 1;
        }
    
        public BigInteger(ulong value)
        {
            data = new uint[maxLength];
    
            // copy bytes from ulong to BigInteger without any assumption of
            // the length of the ulong datatype
    
            dataLength = 0;
            while (value != 0 && dataLength < maxLength)
            {
                data[dataLength] = (uint)(value & 0xFFFFFFFF);
                value >>= 32;
                dataLength++;
            }
    
            if (value != 0 || (data[maxLength - 1] & 0x80000000) != 0)
                throw (new ArithmeticException("Positive overflow in constructor."));
    
            if (dataLength == 0)
                dataLength = 1;
        }
    
        public BigInteger(BigInteger bi)
        {
            data = new uint[maxLength];
    
            dataLength = bi.dataLength;
    
            for (int i = 0; i < dataLength; i++)
                data[i] = bi.data[i];
        }
    
        public BigInteger(byte[] inData)
        {
            dataLength = inData.Length >> 2;
    
            int leftOver = inData.Length & 0x3;
            if (leftOver != 0)         // length not multiples of 4
                dataLength++;
    
    
            if (dataLength > maxLength)
                throw (new ArithmeticException("Byte overflow in constructor."));
    
            data = new uint[maxLength];
    
            for (int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++)
            {
                data[j] = (uint)((inData[i - 3] << 24) + (inData[i - 2] << 16) +
                                 (inData[i - 1] << 8) + inData[i]);
            }
    
            if (leftOver == 1)
                data[dataLength - 1] = (uint)inData[0];
            else if (leftOver == 2)
                data[dataLength - 1] = (uint)((inData[0] << 8) + inData[1]);
            else if (leftOver == 3)
                data[dataLength - 1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]);
    
    
            while (dataLength > 1 && data[dataLength - 1] == 0)
                dataLength--;
    
            //Console.WriteLine("Len = " + dataLength);
        }
    
        public override string ToString()
        {
            return ToString(10);
        }
    
        public string ToString(int radix)
        {
    
            string charSet = "ABCDEF";
            string result = "";
    
            BigInteger a = this;
    
            BigInteger quotient = new BigInteger();
            BigInteger remainder = new BigInteger();
            BigInteger biRadix = new BigInteger(radix);
    
            if (a.dataLength == 1 && a.data[0] == 0)
                result = "0";
            else
            {
                while (a.dataLength > 1 || (a.dataLength == 1 && a.data[0] != 0))
                {
                    singleByteDivide(a, biRadix, quotient, remainder);
    
                    if (remainder.data[0] < 10)
                        result = remainder.data[0] + result;
                    else
                        result = charSet[(int)remainder.data[0] - 10] + result;
    
                    a = quotient;
                }
            }
    
            return result;
        }
    
        private static void singleByteDivide(BigInteger bi1, BigInteger bi2,
                                             BigInteger outQuotient, BigInteger outRemainder)
        {
            uint[] result = new uint[maxLength];
            int resultPos = 0;
    
            // copy dividend to reminder
            for (int i = 0; i < maxLength; i++)
                outRemainder.data[i] = bi1.data[i];
            outRemainder.dataLength = bi1.dataLength;
    
            while (outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength - 1] == 0)
                outRemainder.dataLength--;
    
            ulong divisor = (ulong)bi2.data[0];
            int pos = outRemainder.dataLength - 1;
            ulong dividend = (ulong)outRemainder.data[pos];
    
            if (dividend >= divisor)
            {
                ulong quotient = dividend / divisor;
                result[resultPos++] = (uint)quotient;
    
                outRemainder.data[pos] = (uint)(dividend % divisor);
            }
            pos--;
    
            while (pos >= 0)
            {
                dividend = ((ulong)outRemainder.data[pos + 1] << 32) + (ulong)outRemainder.data[pos];
                ulong quotient = dividend / divisor;
                result[resultPos++] = (uint)quotient;
    
                outRemainder.data[pos + 1] = 0;
                outRemainder.data[pos--] = (uint)(dividend % divisor);
            }
    
            outQuotient.dataLength = resultPos;
            int j = 0;
            for (int i = outQuotient.dataLength - 1; i >= 0; i--, j++)
                outQuotient.data[j] = result[i];
            for (; j < maxLength; j++)
                outQuotient.data[j] = 0;
    
            while (outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength - 1] == 0)
                outQuotient.dataLength--;
    
            if (outQuotient.dataLength == 0)
                outQuotient.dataLength = 1;
    
            while (outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength - 1] == 0)
                outRemainder.dataLength--;
        }
    
    
    
        public static void Main(string[] args)
        {
    
            BigInteger big = new BigInteger(    new byte[]
                                      { 
                                        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 
                                        0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00
                                      });
    
            Console.WriteLine(big);
    
        }
    
    }
    
        4
  •  0
  •   Paul Ruane    15 年前

    System.Decimal 满足你的需求?