简体   繁体   中英

how to convert a concatenate string of characters to decimal numbers

Basically the code below result in in a concatenate string of characters that is placed in "dec". The memory reading from the function which goes through the line of code below is 101E34 which is "dec" should be converted to 163052. How do I convert that string?

   for (int j = 0; j <2; j++)
       {
           char temp[100]= "";
           sprintf(temp, "%x", readArray[j]);
           if (strlen(temp) < 4)
              {
                  char dec[100] = "";
                  for (int r = 0; r < 4 - strlen(temp); r++)
                      {
                          strcat(dec,"0");
                      }
                          strcat(dec, temp);
               }
         }
#include <stdio.h>

int main() {
  char input[] = "101E34";
  char output[100];
  int i = 0, j = 0, k = 0;
  for(i = 0; i < 6;) {
    if(input[i] >= '0' && input[i] <= '9')
      j = (input[i] - '0')<< 4;
    else if(input[i] >= 'A' && input[i] <= 'Z')
      j = (input[i] - 'A' + 10)<< 4;
    else if(input[i] >= 'a' && input[i] <= 'z')
      j = (input[i] - 'a' + 10)<< 4;


    if(input[i + 1] >= '0' && input[i + 1] <= '9')
      j = j + (input[i + 1] - '0');
    else if(input[i + 1] >= 'A' && input[i + 1] <= 'Z')
      j = j + (input[i + 1] - 'A' + 10);
    else if(input[i + 1] >= 'a' && input[i + 1] <= 'z')
      j = j + (input[i + 1] - 'a' + 10);

    k += snprintf((output + k), (100 - k), "%d", j);
    i = i + 2;
  }
  puts(output);
  return 0;
}

The only restriction is on the size of output . You may need to dynamically allocate it if the input is big or changes in every run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM