Pregunta

How can i get the numeric representation of a string in C#? To be clear, I do not want the address of the pointer, I do not want to parse an int from a string, I want the numeric representation of the value of the string.

The reason I want this is because I am trying to generate a hash code based on a file path (path) and a number (line). I essentially want to do this:

String path;
int line;

public override int GetHashCode() {
    return line ^ (int)path;
}

I'm up to suggestions for a better method, but because I'm overriding the Equals() method for the type I'm creating (to check that both object's path and line are the same), I need to reflect that in the override of GetHashCode.

Edit: Obviously this method is bad, that has been pointed out to me and I get that. The answer below is perfect. However, it does not entirely answer my question. I still am curious if there is a simple way to get an integer representation of the value of a string. I know that I could iterate through the string, add the binary representation of that char to a StringBuffer and convert that string to an int, but is there a more clean way?

Edit 2: I'm aware that this is a strange and very limited question. Converting in this method limits the size of the string to 2 chars (2 16 bit char = 1 32 bit int), but it was the concept I was getting at, and not the practicality. Essentially, the method works, regardless of how obscure and useless it may be.

¿Fue útil?

Solución

If all you want is a HashCode, why not get the hashcode of the string too? Every object in .net has a GetHashCode() function:

public override int GetHashCode() {
    return line ^ path.GetHashCode();
}

Otros consejos

For the purposes of GetHashCode, you should absolutely call GetHashCode. However, to answer the question as asked (after clarification in comments) here are two options, returning BigInteger (as otherwise you'd only get two characters in before probably overflowing):

static BigInteger ConvertToBigInteger(string input)
{
    byte[] bytes = Encoding.BigEndianUnicode.GetBytes(input);
    // BigInteger constructor expects a little-endian byte array
    Array.Reverse(bytes);
    return new BigInteger(bytes);
}

static BigInteger ConvertToBigInteger(string input)
{
    BigInteger sum = 0;
    foreach (char c in input)
    {
        sum = (sum << 16) + (int) c;
    }
    return sum;
}

(These two approaches give the same result; the first is more efficient, but the second is probably easier to understand.)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top