C# - Vsprintf equivilant?将Char转换为Int

时间:2017-10-31 17:44:49

标签: c# c

使用vsprintf,下面的c代码将char数组转换为int。我怎么在c#中这样做?我已经尝试将c#字符串转换为int,然后添加值,但返回结果不一样。 我的c#代码需要返回与c代码相同的值(3224115)

C#代码

  var  astring = "123";
        int output = 0;
        foreach(char c in astring){
            var currentChar = (int)c;
            output += c;
        }
//output = 150

C代码

void vout(char *string, char *fmt, ...);                                        
char fmt1 [] = "%d";                                                  

int main(void)                                                                  
{                                                                               
   char string[32];                                                            

   vout(string, fmt1, '123');        //output is 3224115                             
   printf("The string is:  %s\n", string);                                      
}                                                                               
void vout(char *string, char *fmt, ...)                                         

{                                                                               
   va_list arg_ptr;                                                             

   va_start(arg_ptr, fmt);                                                      
   vsprintf(string, fmt, arg_ptr);                                              
   va_end(arg_ptr);                                                             
} 

1 个答案:

答案 0 :(得分:0)

终于想通了。可能有点干净,但它有效,并获得与c代码相同的输出。

 public static ulong getAsciiLiteral(string x)
{
    int len = x.Length;
    string[] strArray = new string[32];
    byte[] finalByte = new byte[32];
    int i = 0;
    int i2 = 0;
    int i3 = 0;
    int offset = 0;
    var hexFinalString = "0x";
    var bytes = Encoding.ASCII.GetBytes(x);

    if(len >= 5)
    {
        while (true)
        {
            if (4 + i3 == len)
            {
                offset = i3;
                break;
            }
            else
            {
                i3++;
            }
        }

    }


    foreach (byte b in bytes)
    {
        strArray[i] = b.ToString("X2");
        i++;
    }
    i = 0;
    i3 = 0;
    while (i3 < len - 1)
    {



        hexFinalString += strArray[offset];
        offset++;
        i3++;
    }


    var ret = Convert.ToUInt64(hexFinalString, 16);
    return ret;

}