Convert ASCII to HEX

Posted on 2006-05-31
Last Modified: 2012-06-27
Are there any easy C++ functions to easily convert from ASCII to Hex and Vice Versa

For example I need to convert a text file containing the following data:|

to a hexadecimal file
Question by:rkbhumagani
    LVL 4

    Accepted Solution

    Use sprintf with %x. You can try something like this:

    char *s = "|";

    int a[8];
    sscanf(s, "%d.%d.%d.%d|%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7]);

    char buf[256];
    sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);

    // write buf to file...
    LVL 4

    Expert Comment

    Are you sure you want hexa and not binary? If you want to write binary, just do this:

    char *s = "|";

    unsigned char a[8];
    sscanf(s, "%d.%d.%d.%d|%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7]);

    // write a to a binary file
    FILE *f = fopen("somefile.dat", "wb");
    fwrite(a, 1, 8, f);


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Live - One-on-One C++ Help from Top Experts

    Solve your toughest problems, fast.
    C++ experts are online now and ready to help you.

    Some Windows API functions expect you to provide a pointer to a CALLBACK function that the system will need to call as part of the operation.  Such API functions as SetTimer, timeSetEvent, CreateThread, EnumWindows, LineDDA, even window message hand…
    C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (…
    The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now