开发者

Reverse a String

Basically I have a method that converts a decimal number to a number in a different base (ex, base 2), the element in position 0 of the array is the most significant, ex $100, The 1 is the most significant.

If i put in a string that is supposed to output AC, I get CA (Dec to hex). How do I reverse this char array in C?

char* decimalToRadixN(int decimalNumber, int radixN, char result[]){
    /*
        If its below base 10, its going to be a digit convertsion (ex to binary)
        If it's above base 10, we need to call a method to convert the char to a symbol. 
     */

        //char swap[] = result[];

    int count = 0; 
    while(decimalNumber>0)
    {
        int remain = decimalNumber % radixN;
        result[count] = decimalToSymbol(remain);
        decimalNumber = decimalNumber / radixN; 
        count++;
    }

    /*
    for(int i = 0; i < count; i++)开发者_StackOverflow中文版
    {
          reverse the array
    }
    */ 
  return result;
}


int i, j;
for( i = 0, j = count - 1; i < j; i++, j-- )
{
    char temp = result[ i ];
    result[ i ] = result[ j ];
    result[ j ] = temp;
}
result[ count ] = '\0';


Not quite the answer to the question as asked, but why not just write the digits in the right order in the first place?

No doubt you didn't know how many digits you needed, hence where to start writing.

This can be done by taking the log of the number to the base of the radix. This can be done using the rules of logarithms.

int numDigitsForRadix(double decimalNumber, double radixN)
{
    double numDigits = log(decimalNumber)/ log(radixN);
    int intDigits = (int)numDigits + 1;
    return intDigits;
}

[ Note also that your 'decimalNumber' is never really a decimal. It is a C int, really binary. This is just naming, and makes not difference. That it appears as base 10 from printf() is the interpretation of printf(), not the number itself.]

Now you have the number of digits in the given base, just write to that digit and decrement rather than increment.

Also, if you pass in the available length of result, you can verify the needed against available length up front and return an error code ( e.g. NULL) if so.

And don't forget to null terminate, or otherwise provide support for returning the length of the written character string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜