Rahul Makwana Rahul Makwana - 3 months ago 10
C Question

bitwise complement of a character in C# vs C overflowexception

I have following code in C which will generate keys based on input serial number.

unsigned int32 passkey(unsigned int32 snumber)
{
char snstring[11];
unsigned int32 pwd;
int i = 0;
itoa(snumber,10,snstring);
do{
snstring[i+1] -= '0';
snstring[i] = ~snstring[i+1];
snstring[i] &= 0x07;
i++;
}while(i < 9);
snstring[9] <<= 1;
snstring[9] &= 0x07;
pwd = atoi32(snstring);
return (pwd);
}


I need to convert this into C# code, I have tried following :

private uint ComputeKey(uint snumber)
{
char[] snstring = new char[11];
UInt32 pwd;
int i = 0;
snstring = snumber.ToString().ToCharArray();

do
{
snstring[i + 1] = Convert.ToChar(snstring[i + 1] - '0');
snstring[i] = Convert.ToChar(~Convert.ToInt32(snstring[i + 1]));
snstring[i] &= Convert.ToChar(Convert.ToInt32(0x07));
i++;
} while (i < 9);
snstring[9] <<= 1;
snstring[9] &= Convert.ToChar(0x07);
pwd = Convert.ToUInt32(snstring);
return (pwd);
}


Programs throws exception at
snstring[i] = Convert.ToChar(~Convert.ToInt32(snstring[i + 1]));
this line.

Another noticeable behavior is that for example I have input as


151972634


Then, on this line
snstring[i] = Convert.ToChar(~Convert.ToInt32(snstring[i + 1]));
value of
snstring[i+1]
is
'\u0005'

And it throws OverflowException was Unhandled.

I am not sure what I should be doing, any help is appreciated.

Answer

I have done a similar task, i.e. to take a number as input and do exactly what your code is doing in C#. I am taking string as input and returning string though. Below is the code :

private string ComputeKey(string serialnumber)
        {
            if (string.IsNullOrEmpty(serialnumber))
            {
                throw new Exception("Cannot generate a key from a null or empty string");
            }

            serialnumber += '\0';
            var length = serialnumber.Length;
            byte[] snbytes = Encoding.UTF8.GetBytes(serialnumber);
            for (int i = 0; i < length - 1; i++)
            {
                snbytes[i + 1] -= 0x30;
                snbytes[i] = (byte)~snbytes[i + 1];
                snbytes[i] &= 0x07;
            }
            snbytes[length - 1] <<= 1;
            snbytes[length - 1] &= 0x07;

            var sb = new StringBuilder();
            for (int j = 0; j < length - 1; j++)
            {
                sb.Append(snbytes[j].ToString());
            }

            return sb.ToString();
        }