-1

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);
               }
         }
m.best
  • 9
  • 1

1 Answers1

-1
#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.

Soumya Kanti
  • 1,429
  • 1
  • 17
  • 28
  • 1
    And, BTW, `main()` should return `int` not `void`. – alk Nov 04 '18 at 11:11
  • Why not? It is a free-standing `C` code, not a library, and the code is meant to give an example. And this program is not meant to run as a service where you need to look into the exit value. I am well aware of `int main(...)` vs `void main()` debate. Unless the `gcc` compiler going to give me error while compiling `void main()`, I will continue to use it. – Soumya Kanti Nov 04 '18 at 12:13
  • 1
    It's is the implementation/environment that is "*free-standing*" or "*hosted*", not the code. And BTW, I did not down-vote. – alk Nov 04 '18 at 16:47