Convert ASCII to HEX

Posted on 2006-05-31
Medium Priority
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
  • 2

Accepted Solution

e_tadeu earned 375 total points
ID: 16803922
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...

Expert Comment

ID: 16803937
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);


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

840 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