0

I am trying to convert a StringBuilder into an Int64 but I get Overflow Exception and I cannot figure out why. The length of the string is not greater than the int. My current code is:

+ $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
 }
3
  • 1
    Please provide minimal sample - you really need one line for this post like Convert.ToInt64("8765432187654321")... after you have such sample you may be able to answer yourself... Commented Jul 30, 2014 at 4:45
  • What are you trying to achieve in this code? All those Converts seems overcomplicated... What I see that you are trying to create Int64 from binary representation stored in strng... Maybe you forgot to add 2 in Convert.ToInt64(Pile.ToString(), 2) Commented Jul 30, 2014 at 4:48
  • And not sure if you really want int value = Convert.ToInt32(letter); as you are using ASCII value of character, so 0 becomes 48, not 0. Commented Jul 30, 2014 at 4:55

1 Answer 1

1

You are converting the ASCII values of a string to their binary values (Convert.ToString(string, 2) converts to base 2, right?)

character -> ASCII value -> Hex string representation -> Int Value -> Binary string representation of int value -> try to parse that string in base 10.

For instance, if "Data" is "147483647", then "Pile" is "110001110100110111110100111000110011110110110100110111" which is clearly larger than 'long.MaxValue' in base 10. By converting each character in a string to the binary representation of their ASCII values, you are creating a number string with far, far more digits than originally when you finally to to parse it base 10.

Just a quick step-through in the debugger should confirm the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.