-4

How to convert str "0xfa" to int 0xfa, str "0x5c" to int 0x5c ?

My code:

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

int main(){

        char a[]="0xfa";
        char b[]="0x5c";
        int c=a;
        int d=b;
        
        //i have to get c to be 0xfa,and d to be 0x5c
        printf("%c%c\n",(char)c,(char)d);
    return 1;
}
A P Jo
  • 446
  • 1
  • 4
  • 15
chenyw1843
  • 129
  • 1
  • 8
  • 4
    just google "convert hex string to char array" – Andy Aug 20 '20 at 00:59
  • 3
    Note that normal programs only return 1 if they failed, otherwise return 0, although this usually makes little practical difference unless you're using it as a terminal tool. – cajomar Aug 20 '20 at 01:20

1 Answers1

1

A character, in C, is an int.

Here, however, you are trying to convert a str with hex val to hex int.

You should use sscanf() , and %x for the formatting.

Or atoi() , strtol().

They are all designed for this exact purpose.

A P Jo
  • 446
  • 1
  • 4
  • 15
  • see [Why shouldn't I use atoi()?](https://stackoverflow.com/q/17710018/995714) – phuclv Aug 20 '20 at 08:55
  • @phuclv Hmm... well , you people here keep worrying about `atoi()` while I go and use my `scanf()`. – A P Jo Aug 20 '20 at 09:42
  • "A character, in C, is an int." --> Not quite. More like a `char`: (or `unsigned char`, `signed char`) C specifies "character" as single-byte character, bit representation that fits in a byte". – chux - Reinstate Monica Aug 20 '20 at 11:00