How to convert byte array to hex string array in C

srini_kandimalla
srini_kandimalla used Ask the Experts™
on
How to convert byte array to hex string array in C.

Provide me sample function.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
jkr
Top Expert 2012

Commented:
To convert a single byte of the array, you can use 'sprintf()' (http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/) with the '%x' format specifier:
char hex[3];
unsigned char my_byte = 0x42;

sprintf(hex,"%2.2x", my_byte);

Open in new window


Now all you need to do is to build that into a loop and apply that to each array element consecutively.

Author

Commented:
When I ran this sample code and try to access hex[3], it is not printing anything and hex[0] is showing as null.
Any better ways?
Top Expert 2012
Commented:
Sorry, should have been
char hex[3];
unsigned char my_byte = 0x42;
int i = (int) my_byte;

sprintf(hex,"%2.2x", i);

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial