溢出例外.StringBuilder

本文关键字:StringBuilder 溢出 | 更新日期: 2023-09-27 18:15:38

我正试图将StringBuilder转换为Int64,但我得到Overflow Exception,我不知道为什么。字符串的长度不大于int型。我现在的代码是:

+ $exception {"Value was either too large or too small for an Int64."} System.Exception {System.OverflowException}

private static Int64 EightBit(string Data)
{
  StringBuilder Pile = new StringBuilder();
  char[] values = Data.ToCharArray();
  foreach (char letter in values)
   {
    // Get the integral value of the character. 
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form. 
    string hexOutput = String.Format("{0:X}", value);
    Pile.Append(Convert.ToString(Convert.ToInt32(hexOutput, 16), 2));
   }
  return Convert.ToInt64(Pile.ToString()); //Error here
 }

溢出例外.StringBuilder

您正在将字符串的ASCII值转换为其二进制值(Convert.ToString(string, 2)转换为2进制,对吗?)

character -> ASCII value ->十六进制字符串表示-> Int value -> Int value的二进制字符串表示 ->尝试以10为进制解析该字符串

例如,"Data"为"147483647",则"Pile"为"110001110100110110111110100111000110011110110110100110111",明显大于"long"。MaxValue' 以10为基数。通过将字符串中的每个字符转换为其ASCII值的二进制表示形式,当您最终以10为基数解析它时,您创建的数字字符串比原来多得多,多得多。

只需在调试器中快速执行一步就可以确认问题。