-4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( int argc, char *argv[] )
{
    char *string = argv[1];
    int i;
    char* p = string;
    for (i=0; i<strlen(string); i++)
    {
        int c;
        for (;p[0] && p[1] && sscanf(p, "%2x", &c); p += 2) printf("%c", c);
    }
    printf("\n");
}

Result

This code works fine when passing an arguement(Hexadecimal) and produces a string. I need the same as a function; when passed a hexadecimal value gives a string.

I tried using a function but there's no output.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int fun (char * s)
{
    char *string = s;    
    int i;
    char* p = string;
    for (i=0; i<strlen(string); i++)
    {
        int c;
        for (;p[0] && p[1] && sscanf(p, "%2x", &c); p += 2) printf("%c", c);
    }
    printf("\n");
}
int main()
{
    fun("Hello");
}

Result

PS: Please go easy on me. I'm new to this.

  • Welcome to SO. Please take some time to provide all required information. "Not working properly" is no useful description. Please provide your sample input, the output and your expected output. – Gerhardh Oct 31 '18 at 09:10
  • The [`scanf` (and family)](https://en.cppreference.com/w/c/io/fscanf) function with the `%x` format expects a pointer to an `int` as argument. It's working the same way as the `"%d"` format, but parses hexadecimal values instead of decimal. – Some programmer dude Oct 31 '18 at 09:11
  • Maybe you want `long value = strtol(argv[1], NULL, 16);` – pmg Oct 31 '18 at 09:12
  • `argv[i]` might be replaced by `argv[1][2*i]` and the loop should probably stop at `i – Gerhardh Oct 31 '18 at 09:13
  • 1
    You also seem to handle `argc` and `argv` very wrong. – Some programmer dude Oct 31 '18 at 09:13
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – Dragonthoughts Oct 31 '18 at 09:13
  • The main problem here is that you attempt to store data in thin air. You never allocate memory. Most likely you want to use `char string[32];` instead. – Lundin Oct 31 '18 at 10:10
  • Sorry for the poor elaboration of the question. – Hariom Saini Oct 31 '18 at 20:22

1 Answers1

0

You can use atoi and snprintf solve it.

The follow code could work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    if (argc != 2)
        return -1;
    char string[32];
    snprintf(string, sizeof string, "0x%08X", atoi(argv[1]));
    printf("%s\n",string);
    return 0;
}
Yunbin Liu
  • 1,444
  • 2
  • 10
  • 20